c++ - 为什么 g++ 与 -O3 段错误与以下 LLVM 库代码

标签 c++ c++11 clang llvm

所以我想使用 llvm::Twine 字符串 block 类。

我有以下示例:

#include <llvm/ADT/Twine.h>
#include <iostream>

int main()
{
  llvm::Twine twine1 = llvm::Twine("aaaa") + "bbbb" + "cccc" + "dddd";
  llvm::Twine twine2 = llvm::Twine(twine1) + "dddd" + "eeee";
  std::cout << twine1.str() << std::endl;
  std::cout << twine2.str() << std::endl;

  return 0;
}

它运行在 clang++-O3g++-O0 但与 g++ 的段错误-O3。我从 3.4-3.9 尝试了这段代码部分不同版本的 clang 库,并尝试使用 g++ 4.8.4g++ 4.8.5mingw-5.3.0.

您需要 llvm 库并将代码与 -lLLVMSupport -lLLVMCorellvm-config --ldflags 中的其他链接

最佳答案

来自 Twine documentation :

A Twine is not intended for use directly and should not be stored, its implementation relies on the ability to store pointers to temporary stack objects which may be deallocated at the end of a statement. Twines should only be used accepted as const references in arguments, when an API wishes to accept possibly-concatenated strings.

换句话说,Twine 对象不拥有它的部分,所以它们在语句结束时被销毁。

正确的用法是:

#include <llvm/ADT/Twine.h>
#include <iostream>

void bar(const llvm::Twine& twine1, const llvm::Twine2& twine2){
    std::cout << twine1.str() << std::endl;
    std::cout << twine2.str() << std::endl;
}

void foo(const llvm::Twine& twine1){
    bar(twine1, twine1 + "dddd" + "eeee");
}

int main()
{
  foo(llvm::Twine("aaaa") + "bbbb" + "cccc" + "dddd");

  return 0;
}  

关于c++ - 为什么 g++ 与 -O3 段错误与以下 LLVM 库代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40071331/

相关文章:

c++ - 并排疯狂 - 在同一台计算机上运行二进制文件

C++ char类型输入,int类型输出

c++ - CRTP与完美转发

c++ - 如何为 reference_wrapper 的 STL 容器设置初始大小?

c++11 - 使用 PCL 迭代最近点进行点云配准

c++ - TrySubmitThreadpoolCallback 未声明的标识符

c++ - 源文件的扩展名

c++ - 为什么编译器不对此进行优化?

c++ - 自动模板推导中的常量正确性

c++ - 限定名称和使用声明的 clang 错误消息