首页 > 解决方案 > Self reference in construction

问题描述

I have just discovered that the following code compiles with both gcc 5.4 and the Intel compiler 18.0.2. Clang 6.0.0 just gives a warning.

#include <vector>

int main() {
  std::vector<double> v = v;

  return 0;
}

I had a bug in my code that was very similar and I am scared that those kind of code can compile. My question are:

标签: c++

解决方案


它是合法的 C++ 吗?如果是,它应该做什么?

这是一个格式良好的程序,但它表现出未定义的行为,因为它读取了一个未初始化的变量。这意味着它的行为没有任何限制(它可以合法地做任何事情)。

如何在编译时捕捉那些“错误”?

启用足够的警告并使用“将警告视为错误”进行构建。发出足够多的警告后,gcc 5.4 会正确捕获它。请注意,在 gcc 的情况下,这也需要打开优化,因为 gcc 只有在优化时才会进行一些分析(例如未使用的变量)。


推荐阅读