Boost python, exposing meyers singleton

I want to do it right. I saw setting boost :: serialization :: singleton here Increase python singleton export level , but I don't want to use this. Instead, I want to use simple meyers singleton.

This code below works, but the documentation says that using http://www.boost.org/doc/libs/1_43_0/libs/python/doc/v2/reference_existing_object.html#reference_existing_object-spec/ is dangerous.

the code:

class Singleton 
{
private:
Singleton(){};

public:
static Singleton & getInstance()
{
    static Singleton instance;
    return instance;
}

int getNumber() { return 5; }
};

And in the module:

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

    ;

What is a good way to do this? Using return_internal_reference<>()led to an error while executing python code.

+3
source share
1 answer

, , , boost:: shared_ptr < > ( - to 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() );
}

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")
+1

All Articles