Question

I have basically two questions may be they are related so I'll put them into one.

Should we pass enum class in C++11 by reference or value when passing to function. It is sort of inheriting primitive type but is it the whole object that is passed? in since enum classes are type safe;

enum class MyEnumClass : unsigned short {
    Flag1 = 0,
    Flag2 = 1,
    Flag3 = 2,
    Flag4 = 4,
};

Now lets say we have function sig

const char* findVal(const MyEnumClass& enumClass);
                                     ^
    should this be by const ref?   __|

my other question is here -

SHOULD IT BE BY MOVE like (MyEnumClass&&) - I am still learning/understanding 
move semantics and rvalue so I am not sure if move semantics are only for 
constructors or can be for member or static funcs -
Was it helpful?

Solution

It is not inheriting the primitive type but rather it tells the implementation to use the specified type(unsigned short) as the underlying type for the enumerators.

You can just simply treat the enum class object as any other class object and apply the same rules while passing it to functions.

  • If you want to modify the enum class object inside function, pass it by reference.
  • If you just want to read the object inside function pass it by constant reference.

Move semantics are a language run-time performance enhancing feature which makes use of opportunities to move from rvalues instead of applying copy semantics which are performance intensive. r-value references and move semantics are not only limited to move constructor and move assignment operator but they can also be used with other functions. If you have scenarios which can make use of this optimization it is perfectly fine to make use of them.

OTHER TIPS

Considering that the enumerators use the specified type unsigned short as an underlying type, as Alok Save pointed out, it is probably a good idea to pass such objects by value (unless you want to change their value in the function as a side effect, in which case you should use a reference.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top