问题
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 }
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
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.
回答5:
typedef enum
{
FIRST_THING,
SECOND_THING
} myType;
Then use it just like an int. Pass it by value.
来源:https://stackoverflow.com/questions/6834581/c-is-it-better-to-pass-an-enum-as-a-value-or-as-a-const-reference