此 C++ 代码是否正确(从枚举标识符创建引用)?
Is this c++ code correct (create reference from enum identifier)?
请检查这段代码中的三种情况。我的评论正确吗?
#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 是糟糕的代码,但需要理解。
枚举标识符的行为类似于 C++ 中的常量。您可以在 C++ 中创建对常量的 const 引用。这还不错。在将枚举常量传递给带有模板参数的函数时,您可能希望使用它们来实现兼容性。
2 与#1 相同
在所有三种情况下,都会创建一个临时对象(枚举器转换为 int 类型的对象)并绑定到常量引用在前两种情况下,临时对象将一直存在,直到引用本身被删除destroyed 即它们具有函数 main 的外部块范围。第三个临时对象将在函数调用结束时销毁。
考虑到在 C++ 中,枚举器在声明时具有枚举类型。
请检查这段代码中的三种情况。我的评论正确吗?
#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 是糟糕的代码,但需要理解。
枚举标识符的行为类似于 C++ 中的常量。您可以在 C++ 中创建对常量的 const 引用。这还不错。在将枚举常量传递给带有模板参数的函数时,您可能希望使用它们来实现兼容性。
2 与#1 相同
在所有三种情况下,都会创建一个临时对象(枚举器转换为 int 类型的对象)并绑定到常量引用在前两种情况下,临时对象将一直存在,直到引用本身被删除destroyed 即它们具有函数 main 的外部块范围。第三个临时对象将在函数调用结束时销毁。
考虑到在 C++ 中,枚举器在声明时具有枚举类型。