g++ 的分段错误(在 NaN 上使用 to_string 两次时)

Segmentation fault with g++ (when using to_string twice on NaN)

假设我们有以下设置:

# CMakeLists.txt
project(Scripts CXX)
add_executable(${PROJECT_NAME} script.cpp)
// script.cpp
#include <limits>
#include <string>

void func()
{
    const double x = std::numeric_limits<double>::quiet_NaN();
    std::to_string(x);
    std::to_string(x);
}

int main()
{
    func();
    return 0;
}

当我们使用 GNU 7.3.0 在 Linux 上以 Release 模式编译 & 运行 时,我们出现段错误:

-- The CXX compiler identification is GNU 7.3.0
-- Check for working CXX compiler: .../gcc-7.3.0/bin/g++
-- Check for working CXX compiler: .../gcc-7.3.0/bin/g++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done

====================[ Build | Scripts | Release ]===============================
.../clion-2020.1.1/bin/cmake/linux/bin/cmake --build .../test_scripts/cmake-build-release --target Scripts --
Scanning dependencies of target Scripts
[ 50%] Building CXX object CMakeFiles/Scripts.dir/script.cpp.o
[100%] Linking CXX executable Scripts
[100%] Built target Scripts

.../test_scripts/cmake-build-release/Scripts
Signal: SIGSEGV (Segmentation fault)

注释掉第二个 to_string(即 //std::to_string(x);)或将 x 更改为非 nan 值(即 x = 10;)或 运行在 Debug 模式下,则没有段错误。

有没有我做错了什么,或者这是一个 g++ 错误?

is this a g++ bug?

是的,这是 7.x 版本中的错误:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86274

它已在 gcc 版本 8 中修复。