C ++:最好将枚举作为值传递或作为const引用传递? [英] 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)如何实现枚举?例如,如果我有代码:
A) How is enum implemented? For example, if I have the code:
enum myType
{
TYPE_1,
TYPE_2
};
实际发生了什么?我知道你可以将TYPE_1和TYPE_2视为int,但是它们实际上只是int?
What is actually happening? I know that you can treat TYPE_1 and TYPE_2 as ints, but are they actually just ints?
B)根据这些信息,假设传入的枚举没有需要更改,将myType作为值或作为const引用传递给函数更有意义吗?
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?
例如,这是更好的选择: / p>
For example, which is the better choice:
void myFunction(myType x){ // some stuff }
或
void myFunction(const myType& x) { // some stuff }
推荐答案
速度明智,事物 - 任何体面的C ++编译器只是要传递一个int。
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?
如果很明显这些枚举实际上只是int,那么我将它们的值传递,就像它们是int。使用const引用可能会导致程序员三思而后行(不是一个好主意)。
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 ++:最好将枚举作为值传递或作为const引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!