C++ 模板的 Clang 优化错误
C++ Clang optimization bug with template
我有一段简单的代码,如下所示:
#include <map>
#include <iostream>
template <typename LocType, typename Base>
class MapWrapper {
public:
Base&& get_and_erase(LocType x) {
Base ret = std::move(_data[x]);
_data.erase(x);
// Uncomment the cout will give correct result
// std::cout << "retval = " << ret << std::endl;
return std::move(ret);
}
void increase(const LocType& x, const Base& w) {
if (w == 0.0) {
return;
}
_data[x] += w;
}
private:
std::map<LocType, Base> _data;
};
int main() {
MapWrapper<int, double> a;
a.increase(1, 1.0);
double w = a.get_and_erase(1);
std::cout << "w = " << w << std::endl;
return 0;
}
我认为输出应该是 1。它在g ++ 4.8.2中工作正常,但是当我使用MAC时
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin14.5.0
Thread model: posix
并编译为:
g++ --std=c++11 -O2 debug.cpp -o debug
我得到的是:
w = 2.64619e-260
我能使其正确的唯一方法是关闭-O2
或通过取消注释代码中的std::cout
来强制输出。
有什么想法吗?
您的代码具有未定义的行为。 get_and_erase
返回对局部变量的引用。启用优化会暴露此错误。您的显式std::move
欺骗了编译器通常会发出的返回对局部变量的引用的警告。
要解决此问题,请将返回类型更改为 Base
,将 return 语句更改为 just return ret;
;此举是不必要的,实际上是一种悲观。
相关文章:
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 是视觉C++优化器错误还是我的代码中有错误?
- SSE 内联汇编和可能的 g++ 优化错误
- 静态局部变量会被错误地优化吗?
- G 4.8.5带负数组索引的循环优化错误
- 未定义的行为或 gcc 优化错误
- 视觉C++ 2017 错误?编译器优化表达式
- 在NDK中启用链接时间优化时,链接器错误
- C1001反量时间的错误(无优化)
- 在VS2017中编译错误C2027,但没有小对象优化
- GCC6.X.中的ConstexPR优化错误
- 优化标志会导致计算错误
- 奇怪的GCC优化错误
- 如何消除只在启用优化的情况下出现的错误
- visual c++中,没有编译器优化的数字代码会给出错误的结果
- C++ 模板的 Clang 优化错误
- LLVM编译器优化错误或什么
- 在osx上使用-O3的g++优化错误
- 这是一个gcc优化错误吗?
- gcc优化错误或违反c++规则