【问题标题】:What happens when std::move() is called without assignment [duplicate]在没有赋值的情况下调用 std::move() 会发生什么
【发布时间】:2020-10-19 21:25:08
【问题描述】:

如果我只使用std::move 而没有任何赋值会发生什么?

std::string s = "Moving";
std::move(s);  //What happens on this line to s?
//is s still valid here?

【问题讨论】:

标签: c++ c++11 move-semantics stdmove


【解决方案1】:

std::move() 不会自行移动传递的对象;它只是可能为对象启用移动语义。它由一个转换组成,您可以使用它的结果来选择(如果可能的话)支持移动语义的适当重载。因此,在您的代码中:

std::string s = "Moving";
std::move(s);

std::move(s) 以上将s 转换为右值引用。不使用铸造的结果。上面的对象s 实际上并没有移动,也没有被修改。

【讨论】:

  • 在我的团队中,我们采取极端立场,如果std::move 用于某事,则将其视为右值引用被利用。即使在您知道右值未被利用的情况下,例如在这种情况下。 (但在这种情况下,它会在代码审查中因为没有目的的无操作而受到抨击。)
  • @Eljay 巧合的是,我在考虑 template<typename T> std::decay_t<T> steal_state(T&& arg) { return std::move(arg); } 来强制移动,即使返回的值没有被使用。由于steal_state() 返回对象按值,并且该对象是从arg移动构造,它移动传递的参数(前提是它不是const-qualified )。
猜你喜欢
  • 2019-06-19
  • 2020-12-30
  • 2020-11-16
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多