Initialization of const reference member with deleted copy constructor

為{幸葍}努か 提交于 2019-12-04 04:38:56

Your example can be reduced to

class A {
public:
    A() = default;
    A(const A&) = delete;
    A& operator=(const A&) = delete;
};

int main()
{
  A a{};
  A const& ar1(a); 
  A const& ar2{a}; // fails on gcc 4.8
}

The initialization of ar2 fails on gcc-4.8 with the error

error: use of deleted function ‘A::A(const A&)’

It compiles cleanly on clang3.4 and gcc4.9. This is the result of the resolution to CWG issue 1288.

N3337 contains the following language for list-initialization:

§8.5.4/3 [dcl.init.list]

List-initialization of an object or reference of type T is defined as follows:
...
— Otherwise, if T is a reference type, a prvalue temporary of the type referenced by T is list-initialized, and the reference is bound to that temporary

This, of course, means that the initialization of ar2 requires an accessible copy-constructor, hence the error.


The language has changed in N3797, where the initialization from an initializer list containing a single element takes precedence over the case quoted above.

— Otherwise, if the initializer list has a single element of type E and either T is not a reference type or its referenced type is reference-related to E, the object or reference is initialized from that element; ...
— Otherwise, if T is a reference type, a prvalue temporary of the type referenced by T is copy-list-initialized or direct-list-initialized, depending on the kind of initialization for the reference, and the reference is bound to that temporary.

So gcc 4.9 and clang 3.4 are implementing the resolution of issue 1288, while gcc 4.8 is following the wording in the C++11 standard.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!