在C ++ 11中访问移动的对象时发出警告 [英] Warn if accessing moved object in C++11

查看:162
本文介绍了在C ++ 11中访问移动的对象时发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

对移动对象可以做什么?

在调用 std :: move 并将结果传递给函数之后,通常必须假定稍后访问移动的对象将会导致未定义的行为。

After you called std::move and passed the result to a function, you generally have to assume that accessing the moved object later will result in undefined behavior.

是否有可以检测到这些访问并警告您的工具。例如:

Are there tools that can detect those accesses and warn you. For example:

{
  Widget w;
  foo(std::move(w));
  // w may be undefined at this point

  w.doSomething(); // WARN
}

至少 gcc 4.7.2 和 clang 3.2 与 -Wall 不要抱怨。

更新:回顾这个问题,关键点是编译器不能决定一个对象在被移动之后是否仍然有效。如果提案 N4034:破坏性移动被接受,我希望编译器有更多的选项(但只有当移动是破坏性的)。

Update: Looking back at this question, the critical point is that the compiler cannot decide whether an object is still valid after it has been moved from. If the proposal N4034: Destructive Move was accepted, I would expect the compiler to have more options (but only if the move is destructive).

推荐答案

。移动类的行为是任何你想要的。这不是编译器应该警告的。

Nor should they. The behavior of a moved-from class is whatever you want it to be. It is not something that a compiler should be warning about.

对于标准库对象,移动类处于有效但未定义的状态。因此,这样做是完全合法的:

For standard library objects, a moved-from class is in a "valid but undefined state". As such, it is perfectly legal to do this:

std::vector<int> v{20, 30, 40};
std::vector<int> v2 = std::move(v);
v = std::vector<int>{50, 60, 70, 80};

清除向量的状态为;它只是清除向量。因此,它被复位到已知状态。类似地, operator = 不关心当前状态是什么;它会将其重置为已知状态。

clear doesn't care what the current state of the vector is; it just clears the vector. Thus it is reset to a known state. Similarly, operator= doesn't care what the current state is; it will reset it to a known state.

这篇关于在C ++ 11中访问移动的对象时发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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