gpt4 book ai didi

c++ - 使用删除的复制构造函数初始化 const 引用成员

转载 作者:可可西里 更新时间:2023-11-01 17:40:32 26 4
gpt4 key购买 nike

此代码在 B 中有一个 const A& a 成员,其中 A 有一个已删除的复制构造函数,在 GCC 中无法编译4.8.1,但它在 clang 3.4 中工作正常:

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

class B{
public:
B(const A& a)
: a{a}
{ }
private:
const A& a;
};

int main()
{
A a{};
B b{a};
}

哪一个编译器是正确的?

GCC 中的错误是:

prog.cpp: In constructor ‘B::B(const A&)’:
prog.cpp:11:14: error: use of deleted function ‘A::A(const A&)’
: a{a}
^
prog.cpp:4:5: error: declared here
A(const A&) = delete;
^

Ideone: http://ideone.com/x1CVwx

最佳答案

你的例子可以简化为

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
}

ar2 的初始化在 gcc-4.8 上失败并出现错误

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

它在 clang3.4 和 gcc4.9 上编译干净。这是 CWG issue 1288 决议的结果.

N3337 包含以下用于列表初始化的语言:

§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

这当然意味着 ar2 的初始化需要一个可访问的复制构造函数,因此会出现错误。


N3797 中的语言发生了变化,其中从包含单个元素的初始化列表中进行的初始化优先于上面引用的情况。

— 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.

所以gcc 4.9和clang 3.4是在实现issue 1288的解决,而gcc 4.8是按照C++11标准的写法。

关于c++ - 使用删除的复制构造函数初始化 const 引用成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24794598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com