下面的代码可以在 Visual Studio 和 g++ 中编译和工作:
class A;
A* getRef(void);
char (&func(...))[2];
int main() {
bool isDefault = sizeof(func(getRef()))==2;
std::cout << isDefault << std::endl; //prints 1
return 0;
}
下一个代码仍然可以在 Studio 中编译(和工作),但是 g++ 声明这是invalid use of incomplete type 'class A'
:
class A;
A& getRef(void); //the only change
char (&func(...))[2];
int main() {
bool isDefault = sizeof(func(getRef()))==2; //g++ error here
std::cout << isDefault << std::endl;
return 0;
}
这是一个根本错误的代码,应该被编译器拒绝(如果是这样,为什么 VS 编译器不产生任何警告)?还是在这种情况下,指针和引用之间实际上存在一些我不知道的区别?
最佳答案
修改后代码的关键方面是将对不完整类型的引用作为实际参数传递给省略号形式参数。
C++11 §5.2.2/7,关于省略号的参数:” The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are performed on the argument expression. An argument that has (possibly cv-qualified) type
std::nullptr_t
is converted to typevoid*
(4.10). After these conversions, if the argument does not have arithmetic, enumeration, pointer, pointer to member, or class type, the program is ill-formed.
然后对于左值到右值的转换,我们发现
C++11 §4.1/1:” A glvalue (3.10) of a non-function, non-array type
T
can be converted to a prvalue. IfT
is an incomplete type, a program that necessitates this conversion is ill-formed.
正如我所读,但这只是我的直觉解释,对 T
的引用是 T
类型的泛左值,这里是不完整的,产生 ill -形成代码。
关于c++ - 不完整类型、引用与指针的无效使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39211727/