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

为君一笑 提交于 2019-11-30 08:21:31

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.

C++ Standard (§7.2/5) guarantees that the underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. So pass it by value and don't make your code more sophisticated that it can be.

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

Yes. They're integral type, and most likely their type is just int because that is most natural type. So you can pass by value; passing by reference wouldn't give you any significant advantage.

By the way, for your reference, the section §7.2/5 says,

The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of sizeof() applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of sizeof() applied to the underlying type.

pass built-in simple types (char, short, int, enum, float, pointers) by value

enums are implemented as integers, you can even explicitly specifiy values for them.

typedef enum
{
    FIRST_THING,
    SECOND_THING
} myType;

Then use it just like an int. Pass it by value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!