我已经构建了一个类工厂,它使用map的本地静态对象来保存它可以创建的所有类的名称:
typedef std::map<std::string, ClassFactory*> typeMap;
static typeMap& getMap() {
static typeMap map;
return map;
}类必须使用以下代码注册到映射:
DerivedRegistering(std::string const& s) {
std::cout << "Inserting " << s << std::endl;
std::cout << "Map size " << getMap().size() << std::endl;
getMap().insert(std::make_pair(s, this));
}如果我想创建一个新实例,我会调用类的静态createInstance函数:
static Object* createInstance(std::string const& s) {
std::cout << "Current map size " << getMap().size() << std::endl;
typeMap::iterator it = getMap().find(s);
if(it == getMap().end()) // not registered
return 0;
return it->second->create();
}假设我在库A的头文件中创建了这个类工厂,并且我将库A动态链接到一个项目中,该项目链接另一个动态库B,并最终创建一个可执行文件。
现在在linux下的gcc我没有遇到任何问题,但是当我在Windows上使用mingw做同样的事情时,我得到了问题。
对gcc的输出:
Registering classes of library B:
Inserting BA
Map size 0
Inserting BB
Map size 1
Inserting BC
Map size 2
Inserting BD
Map size 3
Inserting BE
Map size 4
Registering classes of library A:
Inserting AA
Map size 5
Inserting AB
Map size 6
Inserting AC
Map size 7
Inserting AD
Map size 8
Inserting AE
Map size 9
Inserting AF
Map size 10
Inserting AG
Map size 11
calling create instance in executable:
Current map size 12然而,在mingw中,我得到了如下输出:
Registering classes of library B:
Inserting BA
Map size 0
Inserting BB
Map size 1
Inserting BC
Map size 2
Inserting BD
Map size 3
Inserting BE
Map size 4
Registering classes of library A:
Inserting AA
Map size 0
Inserting AB
Map size 1
Inserting AC
Map size 2
Inserting AD
Map size 3
Inserting AE
Map size 4
Inserting AF
Map size 5
Inserting AG
Map size 6
calling create instance in executable:
Current map size 0因此,在我看来,mingw似乎为每个库和可执行文件创建了一个新的静态本地映射,而gcc则为所有这些库和可执行文件使用相同的内存。
正如您可能猜到的那样,GCC行为就是所需的行为。我可以在mingw中强制执行此操作吗?
发布于 2013-06-10 17:54:49
您的函数是静态的,并且包含在多个位置。这意味着您可以创建截然不同的主体和对象。
在.h中创建外部函数,并在.cpp文件中添加一个正文,这样就有了一个单例。
或者,您可以将其设置为内联,而不是静态,以获得相同的效果。
https://stackoverflow.com/questions/17019083
复制相似问题