gpt4 book ai didi

c++ - 显式删除移动构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:36 27 4
gpt4 key购买 nike

为什么这样:

struct A
{
A(int) {
cout << "construct from int" << endl;
}

A(A&&) = delete;

A(const A &) {
cout << "copy constructor" << endl;
}
};

int main(){
A a = 0;
}

给我一​​个错误:

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

以及为什么当我添加这样的移动构造函数时

A(A&&) {
cout << "move constructor" << endl;
}

它编译得很好,但程序的输出只是

construct from int

据我所知,编译器要求构造函数但不使用它。为什么?这对我来说毫无意义。

附言我假设

A a = 0;

相当于

A a = A(0);

但为什么既不调用移动构造函数也不调用移动赋值运算符?

最佳答案

根据C++标准(12.8复制和移动类对象)

31 When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.122 This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies): .... — when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

30 A program is ill-formed if the copy/move constructor or the copy/move assignment operator for an object is implicitly odr-used and the special member function is not accessible (Clause 11). [ Note: Copying/moving one object into another using the copy/move constructor or the copy/move assignment operator does not change the layout or size of either object. —end note ]

关于c++ - 显式删除移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46749788/

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