Introduction
I recently upgraded the gcc version of a project from 7.5 to 11.4. After the upgrade, I found some exceptions at runtime.
After tracing, it was found that an exception occurred when calling a class member function of a library compiled by gcc-7.5. This class has a private member of type unordered_map, it's constructor will insert some values into unordered_map, while in the function, will take some values from it. The logic is simple, but you will find that the keys in unordered_map are all incorrect
Recurrent
You can use the following sample in ubuntu1804 to reproduce the problem
// 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;
}
Compile Command
g++ kernel.cc -o kernel.o -c --std=c++17
g++-11 test.cpp kernel.o -o test --std=c++17
Execute Command
./test
You will get similar results as follows
Tip
- After testing, it has been found that any combination of g++-7 ~ g++-10 is acceptable. However, if you use a version of g++7 ~ g++10 to compile kernel.o, and use g++-11 ~ g++-13 to compile test.cpp, the problem will recur.
- If you move the position of the kernel.o parameter before test.cpp, the result will be normal again
g++ kernel.cc -o kernel.o -c --std=c++17
g++-11 -o test kernel.o test.cpp --std=c++17