c++ - 不完整类型、引用与指针的无效使用

标签 c++ g++

下面的代码可以在 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 type void* (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. If T is an incomplete type, a program that necessitates this conversion is ill-formed.

正如我所读,但这只是我的直觉解释,对 T 的引用是 T 类型的泛左值,这里是不完整的,产生 ill -形成代码。

关于c++ - 不完整类型、引用与指针的无效使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39211727/

相关文章:

c++ - 为什么在两个不同的类中调用 TinyXPath 时,同一对象会给出不同的结果?

c++ - 套接字在处理后打开,打开它完成

c++ - 使用 g++ mac 包括 GLEW、glfw3 和 glm

c++ - basic_filebuf::underflow 错误读取文件与 ifstream on/proc/pid/stat

gcc - 为什么clang++3.5编译不了这段代码,而clang++3.6可以编译呢?

c++ - 在 OSx 中处理 sigterm

c++ - 检测到堆损坏 | C++

c++ - 用于构建链表的宏

c++ - 奇怪的 undefined reference `vtable

c++ - 无效输入浮点异常的危险是什么?