C++ Boost python,暴露meyers singleton

C++ Boost python,暴露meyers singleton,c++,python,boost,singleton,C++,Python,Boost,Singleton,我想用正确的方式做这件事。我在这里看到了暴露boost::serialization::singleton 但我不想用这个。我想改用简单的meyers单例 下面的代码是有效的,但文档说明使用是危险的 代码: 在模块中: class_<Singleton>("singleton", no_init) .def("getInstance", &Singleton::getInstance, return_value_policy<reference_existing

我想用正确的方式做这件事。我在这里看到了暴露boost::serialization::singleton 但我不想用这个。我想改用简单的meyers单例

下面的代码是有效的,但文档说明使用是危险的

代码:

在模块中:

class_<Singleton>("singleton", no_init)
    .def("getInstance", &Singleton::getInstance, return_value_policy<reference_existing_object>()).staticmethod("getInstance")
    .def("getNumber", &Singleton::getNumber)

    ;
类(“单例”,无初始)
.def(“getInstance”(&Singleton::getInstance,return_value_policy()).staticmethod(“getInstance”)
.def(“getNumber”,&Singleton::getNumber)
;

做这件事的好方法是什么?使用
return\u internal\u reference()
在执行python代码时导致错误。

我们的代码中有很多这样的东西,我没有想到一个简单的方法,但是我们通过使用null deleter从引用返回boost::shared\u ptr来公开它们(我们不知何故将部分代码移到了shared_ptr,而其他代码则没有,所以这是一个混合体)。这并不是最好的做法,但如果您确保在主指针离开后不使用指针,它会按预期工作,并且没有缺陷

对象的生命周期将覆盖解释器,因此在此处将任何引用传递回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() );
}
class_uxy(“XY”,无初始)
.def(“getInstance”,&XY::getSharedInstance)
.staticmethod(“getInstance”)
结构NullDeleter
{
void运算符()(常量void*){}
};
XY&XY::getInstance()
{
静态XY-in;
返回;
}
//这也可以作为独立函数编写,并添加到上面的python类中。
共享_ptr XY::getSharedInstance()
{
返回shared_ptr(&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")
shared\ptr getSharedInstance()
{
返回shared_ptr(&XY::getInstance(),NullDeleter());
}
类(“XY”,无初始)
.def(“getInstance”、&getSharedInstance)
.staticmethod(“getInstance”)

也许标记它C++会引起更多的关注…
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")