考虑以下代码:
class A {
A(const A&);
public:
A() {}
};
int main() {
const A &a = A();
}
此代码在 GCC 4.7.2 下编译良好,但在 Visual C++ 2010 下无法编译并出现以下错误:
test.cc(8) : error C2248: 'A::A' : cannot access private member declared in class 'A'
test.cc(2) : see declaration of 'A::A'
test.cc(1) : see declaration of 'A'
那么在将临时对象绑定(bind)到引用时是否有必要让复制构造函数可访问?
这与我之前的问题有些相关:
Is there a way to disable binding a temporary to a const reference?
最佳答案
So is it necessary to have a copy constructor accessible when binding a temporary to a reference?
后 C++11 - 否
Pre C++11 - 是的。
这段代码在 GCC 4.7.2 下编译良好,因为它符合 C++11 标准。
C++11 标准规定,当从 prvalue
初始化 const 引用时,它必须直接绑定(bind)到引用对象,并且不允许创建临时对象。此外,不使用或不需要复制构造函数。
在 C++11 之前,规则有所不同。并且此行为(是否调用复制构造函数)是实现定义的。 C++03 允许在将 const 引用绑定(bind)到临时对象时调用复制构造函数,因此在 C++11 之后,复制构造函数需要可访问。 Visual C++2010 遵循 C++03 标准。
关于c++ - 临时绑定(bind)到引用是否需要 C++ 中的复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13898750/