Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum class C++11 by reference or value

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 -
like image 807
abumusamq Avatar asked Jul 03 '13 04:07

abumusamq


People also ask

Should enum class be pass by value or reference?

enum class holds an integral value just like a regular enum so you can safely pass it by value without any overhead. Notice that compiler may sometimes optimize pass by reference as well by replacing it with pass by value. But passing by reference may result in some overhead when such an optimization is not applied.

Is enum type or value?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

Can enums have values C++?

Enum, which is also known as enumeration, is a user-defined data type that enables you to create a new data type that has a fixed range of possible values, and the variable can select one value from the set of values.

Can enum class inherit C++?

Not possible. There is no inheritance with enums. You can instead use classes with named const ints.


1 Answers

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.

like image 77
Alok Save Avatar answered Sep 29 '22 20:09

Alok Save