【发布时间】:2014-11-17 13:43:02
【问题描述】:
我有一个带有 main 函数的程序,它只打印一个字符串。当我运行这个程序时,它在控制台中没有输出就崩溃了。当我将元素插入 OperatorCore (symbolMap) 的映射时,我发现问题发生了。
这是最少的代码:
//Binary.hpp
class Binary final : public OperatorCore, public StaticPool<Binary> {
public:
Binary(int ID, std::string name)
: OperatorCore(name), StaticPool<Binary>(ID) {
}
~Binary() {}
};
//Binary.cpp
template<>
const Binary StaticPool<Binary>::pool[] = {
Binary(0, "a string value")//without this line of code, it prints works
};
//OperatorCore.hpp
class OperatorCore {
public:
static std::map<std::string, OperatorCore*> symbolMap;
const std::string name;
OperatorCore (std::string name);
virtual ~OperatorCore () {}
};
//OperatorCore.cpp
std::map<std::string, OperatorCore*> OperatorCore::symbolMap{};
OperatorCore::OperatorCore(std::string name) : name(name) {
symbolMap.insert({name, this});
}
//StaticPool
template<typename T, typename TKey = int>
class StaticPool {
public:
const TKey ID;
static const T pool[];
StaticPool(TKey ID) : ID(ID) {}
virtual ~StaticPool() {}
};
如果我删除突出显示的行之一,则不会出现此问题。这种设计会导致内存损坏吗?
编辑:OperatorCore::symbolMap的初始化在同一个文件中,也是OperatorCore构造函数的实现。
【问题讨论】:
标签: c++ templates inheritance initialization multiple-inheritance