我需要保留一个指向模板化对象的指针的 std::map。 为了摆脱模板,我使用了一个通用的非模板化基类。
运行代码时,我收到一个 SIGSEGV 信号。 调试发现问题出在statement
data_[id] = s;
这可能是与对象初始化顺序有关的问题。
代码如下所示:
文件 shared_iface.h:
class shared_iface {
unsigned long int counter_;
};
文件 shared.h:
extern CommunicationHandler comm;
template <typename T>
class shared: private shared_iface {
public:
shared(): data_(nullptr), id_(0) {
comm.add(id_, this);
}
private:
T* data_;
unsigned long int id_;
};
文件 communication_handler.h:
class CommunicationHandler {
public:
inline void add(unsigned long int id, shared_iface* s) {
data_.add(id, s);
}
private:
Dictionary data_;
};
文件 communication_handler.cpp:
CommunicationHandler comm;
文件 dictionary.h:
class Dictionary {
public:
Dictionary() {
data_.clear();
}
void add(unsigned long int id, shared_iface* s) {
data_[id] = s;
}
private:
std::map<unsigned long int, shared_iface*> data_;
};
文件 main.cpp:
#include "shared.hpp"
shared<int> c;
int main ()
{
return 1;
}
最佳答案
It could be a problem related to the order of initialization of the objects.
一个很好的猜测。 c
是 shared<int>
类型的静态对象. shared<T>
的构造函数取决于静态对象 comm
. c
很可能在 comm
之前初始化你会得到未定义的行为。 comm
本来可以先初始化的,你很幸运,你的代码没有工作。
这被称为 static initialization order fiasco .避免惨败的通常方法是 Construct On First Use Idiom但一般来说,避免依赖于其他静态对象的静态对象。
关于c++ - SIGSEGV 带有指向模板对象的指针的 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30732702/