临时绑定到引用需要在C ++中的复制构造函数吗? [英] Does binding temporary to a reference require a copy constructor in C++?

查看:116
本文介绍了临时绑定到引用需要在C ++中的复制构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

class A {
  A(const A&);
 public:
  A() {}
};

int main() {
  const A &a = A();
}

此代码使用GCC 4.7.2进行编译,但无法使用Visual C ++ 2010出现以下错误:

This code compiles fine with GCC 4.7.2, but fails to compile with Visual C++ 2010 with the following error:

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'

因此,在将临时数据绑定到引用时,是否需要有一个拷贝构造函数?

So is it necessary to have a copy constructor accessible when binding a temporary to a reference?

这与我之前的问题有些相关:

This is somewhat related to my previous question:

Is there a way to disable binding a temporary to a const reference?

推荐答案


因此,在将临时数据绑定到引用时,是否需要有一个复制构造函数?

C ++ 11 - 无

Pre C ++ 11 - 是的。

Post C++11 - No
Pre C++11 - Yes.

此代码使用GCC 4.7.2进行编译,因为它符合C ++ 11标准。

This code compiles fine with GCC 4.7.2 because it is compliant with the C++11 standard.

C ++ 11标准强制要求从 prvalue 初始化const引用时,必须直接绑定到不允许创建引用对象和临时对象。此外,不使用或不需要复制构造函数。

C++11 standard mandates that when a const reference is initialized from prvalue, it must be bound directly to the reference object and no temporary is permitted to be created. Also, the copy constructor is not used or required.

在C ++ 11之前,规则是不同的。而这个行为(是否会调用复制构造函数)是实现定义的。 C ++ 03允许在将const引用绑定到临时的时候调用复制构造函数,因此复制构造函数需要可访问。 Visual C ++ 2010遵循C ++ 03标准。

Prior to C++11 the rules were different. And this behavior(whether copy constructor will be called) is implementation defined. C++03 allowed the copy constructor being called while binding a const reference to an temporary and hence post C++11 the copy constructor needs to be accessible. Visual C++2010 adheres to the C++03 standard.

这篇关于临时绑定到引用需要在C ++中的复制构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆