c++ - 临时绑定(bind)到引用是否需要 C++ 中的复制构造函数?

标签 c++ reference copy-constructor temporary

考虑以下代码:

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/

相关文章:

c++ - 什么是 boost::asio::ssl::context::load_verify_file 以及如何使用它?

c++ - 在 Openmesh 中将网格拆分为连接的组件

c++ - 如何使 Qt Signal 按值发出而不是引用而不会出现编译错误?

c++ - 将复制构造函数与 std::make_shared 结合使用

c++ - std::thread通过引用传递调用复制构造函数

c++ - 类的全局实例(跨多个文件)

c++ - 函数调用参数中的构造函数样式转换

python - 有没有等同于 Perl 中取消引用的 Python?

c++ - 运算符重载 C++ 中返回引用与不返回引用有什么区别

java - 为什么java中不允许分配给 'this'?