提问人:Anoyer 提问时间:11/15/2023 更新时间:11/15/2023 访问量:19
G++11 for unordered_map 与 GCC-11 之前的版本不兼容
g++11 for unordered_map is not compatible with versions earlier than gcc-11
问:
介绍
我最近将一个项目的 gcc 版本从 7.5 升级到 11.4。升级后,我在运行时发现了一些异常。
跟踪后发现,调用gcc-7.5编译的库的类成员函数时出现异常。这个类有一个类型的私有成员,它的构造函数将插入一些值,而在函数中,将从中获取一些值。逻辑很简单,但你会发现里面的键都是不正确的unordered_map
unordered_map
unordered_map
循环的
您可以在 ubuntu1804 中使用以下示例来重现该问题
// kernel.h
#include <memory>
#include <string>
#include <unordered_map>
struct Kernel {
Kernel();
void Print();
private:
std::unordered_map<int, std::shared_ptr<int>> mapping_;
};
// kernel.cc
#include <iostream>
#include "kernel.h"
Kernel::Kernel() {
mapping_[5] = std::make_shared<int>(233);
mapping_[6] = std::make_shared<int>(234);
mapping_[7] = std::make_shared<int>(235);
mapping_[8] = std::make_shared<int>(236);
}
void Kernel::Print() {
for (auto &[key, value] : mapping_) {
std::cout << key << " " << value << " " << *value << std::endl;
}
}
//test.cpp
#include "kernel.h"
int main() {
Kernel kernel;
kernel.Print();
return 0;
}
编译命令
g++ kernel.cc -o kernel.o -c --std=c++17
g++-11 test.cpp kernel.o -o test --std=c++17
执行命令
./test
您将得到类似的结果,如下所示
提示
- 经过测试,发现 g++-7 ~ g++-10 的任何组合都是可以接受的。但是,如果使用 g++7 ~ g++10 版本编译 kernel.o,并使用 g++-11 ~ g++-13 编译 test.cpp,问题会再次出现。
- 如果将 kernel.o 参数的位置移到 test.cpp 之前,结果将再次正常
g++ kernel.cc -o kernel.o -c --std=c++17
g++-11 -o test kernel.o test.cpp --std=c++17
答: 暂无答案
评论