使用Clang优化进行编译时获得意外结果 [英] Getting unexpected result when compiling with clang optimization

查看:196
本文介绍了使用Clang优化进行编译时获得意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中发现了一个错误,该错误仅在启用编译器优化-O1或更高版本时发生.我跟踪了该错误,并且启用优化后,似乎无法在boost转换范围上使用boost type_erased适配器.我写了这个c ++程序来重现它:

I found a bug in my code that only happens when I enable compiler optimizations -O1 or greater. I traced the bug and it seems that I can't use the boost type_erased adaptor on a boost transformed range when optimizations are enabled. I wrote this c++ program to reproduce it:

#include <iostream>
#include <vector>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/adaptor/type_erased.hpp>

using namespace boost::adaptors;
using namespace std;

int addOne(int b) {
  return b + 1;
}

int main(int, char**) {
  vector<int> nums{ 1, 2, 3 };

  auto result1 = nums | transformed(addOne) | type_erased<int, boost::forward_traversal_tag>();
  auto result2 = nums | transformed(addOne);
  auto result3 = nums | type_erased<int, boost::forward_traversal_tag>();

  for (auto n : result1)
    cout << n << " ";
  cout << endl;

  for (auto n : result2)
    cout << n << " ";
  cout << endl;

  for (auto n : result3)
    cout << n << " ";
  cout << endl;
}

当我在没有任何优化的情况下运行该程序时,将得到以下输出:

When I run this program without any optimizations, I get the following output:

2 3 4
2 3 4
1 2 3

当我使用-O1标志运行它时,我得到以下信息:

When I run it with the -O1 flag, I get the following:

1 1 1
2 3 4
1 2 3

我正在使用clang ++对其进行编译.我正在使用的Clang版本是:

I am using clang++ to compile it. The version of clang that I am using is:

Apple LLVM版本8.0.0(clang-800.0.38)

Apple LLVM version 8.0.0 (clang-800.0.38)

我不知道我是否做错了什么,或者它是否是Boost/Clang错误.

I don't know if I am doing something wrong, or if it is a boost/clang bug.

将其更改为

type_erased<int, boost::forward_traversal_tag, const int>()

,现在可以使用.第三个模板参数是引用类型,将引用设置为const可以延长由转换对象创建的临时对象的时间跨度.

and it works now. The third template argument is the reference type, setting the reference to const prolongs the timespan of the temporary created by the transformed.

推荐答案

使用

type_erased<int, boost::forward_traversal_tag, const int>()

有效.第三个模板参数是引用类型,将引用设置为const可以延长由转换对象创建的临时对象的时间跨度.

works. The third template argument is the reference type, setting the reference to const prolongs the timespan of the temporary created by the transformed.

这篇关于使用Clang优化进行编译时获得意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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