gpt4 book ai didi

c++ - move 赋值运算符和 move 构造函数之间的区别?

转载 作者:IT老高 更新时间:2023-10-28 23:14:02 24 4
gpt4 key购买 nike

一段时间以来,这一直让我感到困惑。到目前为止,我还没有找到满意的答案。问题很简单。什么时候调用move assignment operator,什么时候调用move constructor operator

cppreference.com 上的代码示例产生了以下有趣的结果:

The move assignment operator:

a2 = std::move(a1); // move-assignment from xvalue

The move constructor:

A a2 = std::move(a1); // move-construct from xvalue

那么它与哪个实现有关?如果是这样,如果两者都实现,则执行哪个?以及为什么有可能创建一个 move 赋值运算符重载,如果它无论如何都是相同的。

最佳答案

只有在构造对象时才会执行 move 构造函数。在先前构造的对象上执行 move 赋值运算符。这与复制案例中的场景完全相同。

Foo foo = std::move(bar); // construction, invokes move constructor
foo = std::move(other); // assignment, invokes move assignment operator

如果您没有显式声明它们,编译器会为您生成它们(有一些异常(exception),列表太长,无法在此处发布)。

this有关何时隐式生成 move 成员函数的完整答案。

关于c++ - move 赋值运算符和 move 构造函数之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29971205/

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