Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

oop

enums

Since its called a 'class' I would usually pass it as const reference, but if I use a plain enum it makes no difference right? So does it make a difference if I pass a enum class as value/const ref? Also, does the type matter? For example a enum class:int

like image 693
AutobahnPolizei Avatar asked Jun 25 '17 19:06

AutobahnPolizei


People also ask

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 .

Should enum be in header or CPP?

Your code (e.g. your enum) SHOULD be placed in the . h file if you need to expose it to the code you're including the . h file. However if the enum is only specific to the code in your header's .

Is enum a const?

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.

What is the difference between a class enum and a regular enum?

Difference between Enums and Classes An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).


2 Answers

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.

like image 180
user7860670 Avatar answered Sep 21 '22 12:09

user7860670


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

There are exceptions to this rule; and indeed the trendies nowadays like to rely on pass by value followed by move semantics when building copy constructors for example.

For the new enum class stuff of C++11, pass it by value (after all it only holds an integral type under the hood) and trust the compiler to make the optimisations.

If you are ever in any doubt, profile any performance differences.

like image 41
Bathsheba Avatar answered Sep 18 '22 12:09

Bathsheba