我想以正确的方式去做。我在这里看到了 boost::serialization::singleton Boost python export singleton但我不想使用它。我想改用简单的 meyers 单例。
下面的代码有效,但文档说使用 http://www.boost.org/doc/libs/1_43_0/libs/python/doc/v2/reference_existing_object.html#reference_existing_object-spec/很危险。
代码:
class Singleton
{
private:
Singleton(){};
public:
static Singleton & getInstance()
{
static Singleton instance;
return instance;
}
int getNumber() { return 5; }
};
在模块中:
class_<Singleton>("singleton", no_init)
.def("getInstance", &Singleton::getInstance, return_value_policy<reference_existing_object>()).staticmethod("getInstance")
.def("getNumber", &Singleton::getNumber)
;
有什么好的方法吗?使用 return_internal_reference<>()
执行 python 代码时导致错误。
最佳答案
我们的代码中有很多这样的东西,我还没有想出一个简单的方法,但是我们通过从带有空删除器的引用中返回 boost::shared_ptr<> 来公开它们(我们以某种方式移动了部分代码到 shared_ptr 而其他人不是,所以这是一个混合物)。这不是最好的做法,但它按预期工作并且没有陷阱,如果你确保在离开 main 之后不对指针做任何事情。
您的对象的生命周期将超过解释器,因此您不必担心在此处将任何引用传回 python 时出现任何问题。该库只会在解释器退出后释放(可能调用或不调用您的析构函数,有时可能会出现一个整体,以防出现错误等)。因此,在这种情况下,您可以将解释器视为经典的 main() 函数。
class_<XY, shared_ptr<XY>, boost::noncopyable >("XY",no_init)
.def("getInstance",&XY::getSharedInstance )
.staticmethod("getInstance")
struct NullDeleter
{
void operator()(const void*){}
};
XY& XY::getInstance()
{
static XY in;
return in;
}
// This can also be written as a standalone function and added to the python class above.
shared_ptr<XY> XY::getSharedInstance()
{
return shared_ptr<XY>( &getInstance(), NullDeleter() );
}
或者你可以将 sharedInstance 非侵入式地写成一个单独的函数,然后在 python 包中使用它:
shared_ptr<XY> getSharedInstance()
{
return shared_ptr<XY>( &XY::getInstance(), NullDeleter() );
}
class_<XY, shared_ptr<XY>, boost::noncopyable >("XY",no_init)
.def("getInstance",&getSharedInstance )
.staticmethod("getInstance")
关于c++ - Boost python,暴露迈耶斯单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10738776/