gpt4 book ai didi

c++ - 回退到复制构造函数不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:16:50 25 4
gpt4 key购买 nike

我认为当我删除 B 中的 move 构造函数时,下面的代码仍然可以正常编译,因为它仍然应该使用复制构造函数来构造 B 对象。为什么编译器现在会提示。没有 =delete 它就不会调用复制构造函数,因为它不允许提供默认的 move 构造函数!)

class B{
public:
B(){}
~B(){}
B & operator=(const B & b){
std::cout << " cannot move -> copy " << std::endl;
return *this;
}
B(const B & v){
std::cout << " cannot move -> copy " << std::endl;
}

// B(B && b) = delete; // uncomment this!
};


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

clang 3.6 的编译器输出 ( Live code )

main.cpp:27:7: error: call to deleted constructor of 'B'

B b( B{} );

^ ~~~

main.cpp:21:5: note: 'B' has been explicitly marked deleted here

B(B && b) = delete;

^

1 error generated.

最佳答案

定义被删除的函数仍然被声明。除其他事项外,它正常参与重载决议 - 但如果重载决议实际选择它,则程序格式错误([dcl.fct.def.delete]/2):

A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed. [ Note: This includes calling the function implicitly or explicitly and forming a pointer or pointer-to-member to the function. It applies even for references in expressions that are not potentially-evaluated. If a function is overloaded, it is referenced only if the function is selected by overload resolution. —end note ]

这与从未声明过的函数不同。不存在的声明当然不参与重载决议。

关于c++ - 回退到复制构造函数不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29879834/

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