带有std::指向模板对象的指针映射的SIGSEGV
SIGSEGV with std::map of pointers to template objects
我需要保存一个指向模板化对象的指针的std::map。为了摆脱模板,我使用了一个普通的非模板基类。
当运行代码时,我得到一个SIGSEGV信号。调试显示,问题出现在语句
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;
}
可能是与对象初始化顺序有关的问题。
猜得好。c
是shared<int>
类型的静态对象。shared<T>
的构造函数依赖于静态对象comm
。c
很可能在comm
之前初始化,你会得到未定义的行为。comm
可以先初始化,你很幸运,你的代码没有工作。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- sigsegv在没有指针的线上
- 尝试将返回无符号值的函数分配给指向无符号的指针时,继续获取 SIGSEGV
- 程序在调用类指针时收到信号SIGSEGV,分段错误
- 修改指针会导致 SIGSEGV 信号
- C++ 通过共享指针将值分配给结构成员会导致 SIGSEGV
- 指向结构的指针的动态数组在成员变量赋值时抛出 SIGSEGV
- 带有std::指向模板对象的指针映射的SIGSEGV