为什么不能将函数中变量的最后一个赋值视为移动? [英] Why can't the last assignment from a variable in a function be treated as a move?

查看:50
本文介绍了为什么不能将函数中变量的最后一个赋值视为移动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这样的代码中:

class X {
  X(const X&) {
    // ...
  }

  X(const X&&) {
    // ...
  }

  // ...
};

void f() {
  X a;
  // ...
  X b = a;
  // ... code that doesn't use a
}

我的理解是,最后一条语句调用复制构造函数而不是move构造函数。假设 a 不再在 f()中使用,编译器能否自动优化该语句以使用move构造函数代替?

My understanding is that the last statement calls the copy constructor not the move constructor. Assuming a is never used again in f(), can the compiler automatically optimize this statement to use the move constructor instead?

PS我知道 std :: move(),但是我在问自动移动。

P.S. I know about std::move(), but I'm asking about automatic move.

推荐答案

您需要编写可以正确处理的规范

You'd need to write a spec that somehow correctly handles

void f() {
  X a;
  g(a); // stash a reference to a somewhere 
  X b = a; // can't move from a!
  g2(); // use the reference stored by g
}

为了安全起见,您可以需要证明后续代码(包括其调用的所有函数)不会直接或间接访问 a ,这在一般情况下是不可能的,因为这些函数的定义可能对编译器不可用(例如,在不同的翻译单元中)。

For the move to be safe, you'd need to prove that subsequent code, including all the functions it calls, does not access a directly or indirectly, which is impossible in the general case because the definitions of these functions may not be available to the compiler (e.g., in a different translation unit).

这篇关于为什么不能将函数中变量的最后一个赋值视为移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆