我在较大的 C++ 应用程序中遇到了一个问题,该问题仅在启用优化时才会发生
-O
、-O2
或 -O3
。我设法使用以下代码片段重现了该问题:
#include <string>
#include <memory>
#include <fstream>
#include <iomanip>
#include <iostream>
class PriceFeedStream {
private:
std::string trades_file_name = "example.csv";
std::ofstream output_trades_file;
public:
PriceFeedStream(const std::string& assetName){
std::cout << "trying to initialize " << std::endl;
output_trades_file.open(trades_file_name, std::ios::app);
if (!output_trades_file) {
std::cerr << "failed to open file: " << trades_file_name << std::endl;
return;
}
output_trades_file << assetName << std::endl;
}
};
int main(){
std::string asset = "ABC3";
std::cout << "initializing feed map with asset " << asset << std::endl;
std::unique_ptr<PriceFeedStream> feed = std::make_unique<PriceFeedStream>(asset);
std::cout << "done" << std::endl;
return 0;
}
应用程序在Windows上编译,使用编译器版本:
g++.exe (MinGW-W64 x86_64-ucrt-mcf-seh, built by Brecht Sanders) 13.2.0
在没有任何优化标志的情况下编译时:
g++ -g -Wall -Werror -Wextra -std=c++20 main.cc -o main
运行可执行文件的输出是:
initializing feed map with asset ABC3
trying to initialize example.csv
done
启用优化标志进行编译:
g++ -g -Wall -Werror -Wextra -std=c++20 -O2 main.cc -o main
运行可执行文件时产生以下结果:
initializing feed map with asset ABC3
Segmentation fault
我的猜测是代码可能有一些未定义的行为,导致在没有优化标志的情况下不会出现此段错误。我想了解这是什么类型的问题,以便在未来的情况下缓解。
这个问题确实与 @SamVarshavchik 提到的编译器的选择有关,不确定根本原因。我在同一台 Windows 机器上安装了 Clang/LLVM。
clang --version
(built by Brecht Sanders) clang version 16.0.6
Target: x86_64-w64-windows-gnu
Thread model: posix
InstalledDir: C:/mingw64/bin
编译代码后
clang++ -g -Wall -Werror -Wextra -std=c++20 -O2 main.cc -o main
应用程序按预期执行:
initializing feed with asset ABC3
trying to initialize
done