Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is it better to pass an enum as a value or as a const reference?

There are sort of two related questions here:

A) How is enum implemented? For example, if I have the code:

enum myType {     TYPE_1,    TYPE_2 }; 

What is actually happening? I know that you can treat TYPE_1 and TYPE_2 as ints, but are they actually just ints?

B) Based on that information, assuming that the enum passed in didn't need to be changed, would it make more sense to pass myType into a function as a value or as a const reference?

For example, which is the better choice:

void myFunction(myType x){ // some stuff } 

or

void myFunction(const myType& x) { // some stuff } 
like image 783
Casey Patton Avatar asked Jul 26 '11 18:07

Casey Patton


People also ask

Should enums be passed by const reference?

"Plain" enums and enum class objects both are of integral type, so the decision of passing by const reference or by value is just the same as if you did for other arguments of integral type.

Should enums be constants?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.

Is enum value or reference?

An enum type is a distinct value type (§8.3) that declares a set of named constants. declares an enum type named Color with members Red , Green , and Blue .

Why is enum faster?

Enum values will take more memory compared to an int constant. Adding a single enum will increase the size of the final DEX file approximately 13x when to an integer constant. This is because each value in an enum class is treated as an object, and each value will take some heap memory to reference the object.


1 Answers

Speed wise it almost certainly doesn't matter - any decent C++ compiler is just going to pass a single int.

The important point is readability - which will make your code more obvious to the reader?

If it's obvious that these enums are really just ints then I would pass them by value, as if they were ints. Using the const ref might cause a programmer to think twice (never a good idea!)

However - if you are later going to replace them with a class then keeping the API the same and enforcing the const-ness might make sense.

like image 98
Martin Beckett Avatar answered Sep 23 '22 13:09

Martin Beckett