我在Ubuntu上的动态库A.so中以这种方式实现Meyers singleton时遇到了问题:
class Singleton
{
/*some functionality*/
}
Singleton& getSingleton(); // in header file
Singleton& getSingleton() // in .cpp file
{
static Singleton value;
return value;
}函数getSingleton()在other库B.so类型的对象的构造函数和析构函数中调用,如下所示:
class User
{
User()
{
getSingleton().addSmth();
}
~User()
{
getSingleton().removeSmth();
}
/*some other functionality*/
};类用户的对象创建为静态对象,该对象是B.so中某些函数的静态对象。
因此,在从其他Singleton类的析构函数调用之前,我面临着销毁User对象的问题。
我的项目有多个库,它是在Ubuntu20.04上用CMake和gcc-10.3构建的.我需要帮助修复Singleton的对象生命周期
我在Windows 10上的Visual中检查了相同的项目,并且运行良好
发布于 2022-04-27 18:01:38
请记住,破坏的顺序是相反的建筑。因此,您必须确保在使用Singleton的其他静态对象(让我们称之为SingletonClient)之前初始化它。所以,就像这样:
struct SingletonClient {
SingletonClient() {
getSingleton(); // makes sure the other object is constructed before this one
}
};https://stackoverflow.com/questions/72033277
复制相似问题