【问题标题】:C++20 std::move in self assignmentC++20 std::move 中的自赋值
【发布时间】:2021-01-13 02:23:04
【问题描述】:

包括this 在内的大多数答案都指出std::move 并不打算用于自我分配。
但是,我确实通过 self move assignment 在官方reference 中看到了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;
}

只有从 C++20 开始才安全吗?内部发生了什么?
EXP63-CPP 声明:

应该假设唯一可以对移出对象实例安全执行的操作是通过分配给对象重新初始化或通过调用其析构函数来终止对象的生命周期

看起来重新初始化是完全合法的。

【问题讨论】:

  • 这不是官方参考。您无需付费即可获得最接近官方参考资料的是标准草案。
  • 这个例子是将init移动到operator+而不是operator=

标签: c++ c++20 stdmove


【解决方案1】:

这不是自我分配。

自分配是init = std::move(init);,而你有init = std::move(init) + *first;

【讨论】:

  • 您能否详细说明 [self-assignment] 和 [not self-assignment contains self-move] 之间 init 对象状态的差异。我会完全接受你的回答
  • @user2376997 我不确定如何在这里详细说明。重载的+ 通常按值返回,而不是对其左操作数的引用。如果它返回对您的类型的左操作数的引用,那么是的,这将是一个自赋值。
猜你喜欢
  • 2020-08-06
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 2017-05-28
  • 1970-01-01
  • 2014-12-19
相关资源
最近更新 更多