我在 C++ 中动态加载一个库,如此处所述。
我的抽象基类如下所示:
#include <boost/ptr_container/ptr_list.hpp>
class Base {
public:
virtual void get_list(boost::ptr_list<AnotherObject>& list) const = 0;
};
我的库现在提供了一个派生类Derived
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));
}
和create
和destroy
函数
extern "C" {
Base* create() { new Derived; }
destroy(Base* p) { delete p; }
}
我的客户端程序加载库和两个create
和destroy
函数。然后它创建一个实例Derived
并使用它:
Base* obj = create();
boost::ptr_list<AnotherObject> list;
obj->get_list(list);
现在我的问题:当列表被库填充时,new
调用库来创建AnotherObject
s。另一方面,当列表被销毁时,delete
调用客户端来销毁AnotherObject
s。我能做些什么来避免这个问题?