简体   繁体   English

C++20 std::move 在自赋值中

[英]C++20 std::move in self assignment

Most answers, including this one, point out that std::move is not meant to be used in self-assignment.大多数答案,包括这个答案,都指出std::move不打算用于自赋值。
I do, however, see the Possible Implementation of accumulate in official reference via self move assignment:但是,我确实通过自移动分配在官方参考中看到了accumulate可能实现

template<class InputIt, class T>
constexpr // since C++20
T accumulate(InputIt first, InputIt last, T init)
{
    for (; first != last; ++first) {
        init = std::move(init) + *first; // std::move since C++20
    }
return init;
}

Is it safe only since C++20?只有从 C++20 开始才安全吗? What is happening internally?内部发生了什么?
The EXP63-CPP states that: EXP63-CPP声明:

it should be assumed that the only operations that may be safely performed on a moved-from object instance are reinitialization through assignment into the object or terminating the lifetime of the object by invoking its destructor应该假设唯一可以在移出的对象实例上安全执行的操作是通过分配给对象重新初始化或通过调用其析构函数终止对象的生命周期

Looks like reinitialization is completely legal.看起来重新初始化是完全合法的。

This is not a self-assignment.这不是自我分配。

A self-assignment would be init = std::move(init);自赋值将是init = std::move(init); , and you have init = std::move(init) + *first; ,你有init = std::move(init) + *first; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM