Transfer boost :: ptr_list from the library to the client

I am dynamically loading the library in C ++ as described here .

My abstract base class is as follows:

#include <boost/ptr_container/ptr_list.hpp> class Base { public: virtual void get_list(boost::ptr_list<AnotherObject>& list) const = 0; }; 

And my library now provides Derived derived class

 class Derived : public Base { ... }; void Derived::get_list(boost::ptr_list<AnotherObject& list) const { list.push_back(new AnotherObject(1)); list.push_back(new AnotherObject(2)); } 

and create and destroy functions

 extern "C" { Base* create() { new Derived; } destroy(Base* p) { delete p; } } 

My client program loads a library and two create and destroy functions. He then creates an instance of Derived and uses it:

 Base* obj = create(); boost::ptr_list<AnotherObject> list; obj->get_list(list); 

Now my problem is: when the list is populated with a library, the new library is called to create AnotherObject s. On the other hand, when the list is destroyed, the delete client is called to destroy AnotherObject s. What can I do to avoid this problem?

+1
c ++ boost linux shared-libraries
source share
3 answers
  • Use std::list<shared_ptr<AnotherObject> > .
  • Passing the user deletion to shared_ptr, which causes the proper deletion.
+3
source share

The easy answer is to insist that both the application and the library are compiled with the same version of the compiler, in which case they will both receive the same new / deleted versions.

0
source share

It is best to have one new operator and one delete operator for the entire program. There are linking options that can help (I remember -Wl, - export-dynamic, but this may be for a different but related problem).

If this is not possible, make sure that all delete operations are performed by the same object as the new one, so do not define them in the built-in functions.

0
source share

All Articles