C ++ - is it better to pass the enum class as a value or reference to const?

Since it is called a "class", I usually passed it as a reference to const, but if I use a simple enumeration, does it make any difference? So what does it matter if I pass the enum class as value / const ref? Also, is the type relevant? For example, the class enum: int

+4
source share
6 answers

enum classstores an integer value as usual enum, so you can safely transfer it at a cost without any overhead. Please note that the compiler can sometimes optimize the transfer by reference, replacing it with the transfer by value. But passing by reference can lead to some overhead if such optimization is not applied.

+7
source

As a very broad rule of thumb, pass simple old data types as values, and class instances as const.

There are exceptions to this rule; and really fashionable trends nowadays like to rely on a pass by value, followed by movement semantics when building copy constructors, for example.

enum class ++ 11 ( ) .

- , .

+3

. , , , . . .

, .

, , const , ( , "class" ). , .

+2

"" enum , , .

"" , , - "". , (const) , , .

: : " ". /, .

, , , (, ) , .

int 4 , "" ( ) 8 . , , .

, , . unsigned char, , .

enum class ColorsEnumClass : unsigned char {
    red,
    green,
    blue
};
+1

, . , .

, , .

0

, . , , . , - int enum enum. , int.
enum enum . , . enum .

enum class light_color {red, yellow, green};
enum class car_color {red, yellow, green};

void myFunc(car_color) {}


int main() {
    myFunc(car_color::red);    // this one will compile fine
    myFunc(light_color::red);  // this one will give you error at compile time
}

, . , .

-3
source

Source: https://habr.com/ru/post/1680078/


All Articles