gpt4 book ai didi

c++ - 即使成员没有移动构造函数,移动构造函数也会自动生成?

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

引自 C++ Primer

if we explicitly ask the compiler to generate a move operation by using = default, and the compiler is unable to move all the members, then the move operation will be defined as deleted

the move constructor is defined as deleted if the class has a member that defines its own copy constructor but does not also define a move constructor, or if the class has a member that doesn’t define its own copy operations and for which the compiler is unable to synthesize a move constructor

有些代码似乎违反了这条规则:

#include <utility>
#include <iostream>

struct X {
X() = default;
X(const X&) { std::cout << "X(const X&)" << std::endl; }
int i;
};

struct hasX {
hasX() = default;
hasX(const hasX &) = delete;
hasX(hasX &&) = default;
X mem;
};


int main()
{
hasX hx, hx2 = std::move(hx); //output is X(const X&)
}

X 没有定义移动构造函数,编译器不能为它合成一个。

根据上面的规则,hasX的移动构造函数被删除。

但是,由于hasX的复制构造函数被删除,hx2 = std::move(hx)必须调用move构造函数输出"X(const X&)",显示hasX的移动构造函数已定义,它使用X的复制构造函数进行“移动”。这似乎违反了上述规则。

那么,是不是在 C++ 标准中定义了,或者只是一个编译器实现?

我测试的编译器:VS2015 和 a online compiler

谢谢你的帮助!

最佳答案

你的书好像错了。 Copying is a valid move operation因此,只要成员具有 const type& 形式的复制构造函数,它就可以绑定(bind)到右值,移动操作将回退到拷贝。

在你的例子中

hasX(hasX &&) = default;

可以替换为

hasX(hasX &&rhs) : mem(std::move(rhs.mem)) {}

因为这就是默认值,它会编译得很好。

关于c++ - 即使成员没有移动构造函数,移动构造函数也会自动生成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44683115/

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