请检查这段代码中的三种情况。我的评论正确吗?
#include <iostream>
using namespace std;
enum Test {
T1 = 0,
T2,
T3
};
void f(const int &v)
{
cout << v << endl;
}
int main() {
const int &t = T2; // #1: is there reference to temporary int object?
const int &t1(T1); // #2: same as #1?
f(T3); // #3: is there creation of temporary int object and passing it by reference?
return 0;
}
案例 #1、#2 是糟糕的代码,但需要理解。
最佳答案
在所有三种情况下,都会创建一个临时对象(枚举数转换为 int 类型的对象)并绑定(bind)到常量引用在前两种情况下,临时对象将一直存在,直到引用本身被销毁它们是否具有函数 main 的外部 block 范围。第三个临时对象将在函数调用结束时销毁。
请注意,在 C++ 中,枚举器在声明它们的位置具有枚举类型。
关于c++ - 此 C++ 代码是否正确(从枚举标识符创建引用)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28840735/