c++ - SIGSEGV 带有指向模板对象的指针的 std::map

标签 c++ templates inheritance g++ stdmap

我需要保留一个指向模板化对象的指针的 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.

一个很好的猜测。 cshared<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/

相关文章:

c++ - 如何在Qt中使用FontAwesome

c++ - 如何使用 std::conditional 选择一个自由函数

java - 将嵌套类继承到子类

java - 我需要知道控制流是什么以及这段代码到底发生了什么?

C++ 纯虚 const 成员函数

c++ - CMake:find_package 中的项目如何破坏程序?

c++ - 关于字符串操作

继承模板类中的 C++ 编译器错误

c++ - 返回 const 模板类型的模板函数

c++ - 为什么继承的构造函数不应该继承默认参数?