c++ - 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:
- Is it legal C++? If yes, what is it supposed to do?
- How to catch those "bugs" at compile time?
解决方案
它是合法的 C++ 吗?如果是,它应该做什么?
这是一个格式良好的程序,但它表现出未定义的行为,因为它读取了一个未初始化的变量。这意味着它的行为没有任何限制(它可以合法地做任何事情)。
如何在编译时捕捉那些“错误”?
启用足够的警告并使用“将警告视为错误”进行构建。发出足够多的警告后,gcc 5.4 会正确捕获它。请注意,在 gcc 的情况下,这也需要打开优化,因为 gcc 只有在优化时才会进行一些分析(例如未使用的变量)。
推荐阅读
- python - 根据其他熊猫列中列表中的值数量创建新列?
- flutter - 如何优化 SingleChildRenderObjectWidget 以便重复使用?
- power-automate - 使用强力自动化将任务从一个计划者复制到另一个计划者
- r - 多次随机采样向量以进行分组并进行方差分析
- python - 如何将嵌套函数数据发送到python中的另一个函数
- flutter - 如何用颤振解决真实设备上的相机和存储文件权限
- kotlin - 协程比 Kotlin 中的 Thread 快吗?为什么?如何获得“上下文切换”的时间?
- c++ - C++ Linked List 删除整个列表而不是仅删除 1 个节点
- discord - 余额应如下所示 1,000
- asp.net-core - IIS 8.5 上的 ASP.Net Core 3.1 - 默认路由出现 404 错误