我有一个函数名为 void deallocatorFunc(ClassA *p)
的类我希望使用模板可以编写 boost::shared_ptr< ClassA > ptr(new ClassA());
而不是 boost::shared_ptr< ClassA > ptr(new ClassA(), deallocatorFunc);
.我希望它传播到我的类(class)及其继承人。如何在 C++ 中做这样的事情? (我真的需要那个特殊类的特殊析构函数,同时我想保持 super 简单的 API)。
最佳答案
您可以为您的类使用专门化并包装标准实现。这是一个独立的可编译示例。
#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;
class A
{
public:
A() {
cout << "Constructing A." << endl;
};
virtual ~A() {
cout << "Destructing A." << endl;
}
};
class B : public A
{
public:
B() {
cout << "Constructing B." << endl;
};
virtual ~B() {
cout << "Destructing B." << endl;
}
};
class C
{
public:
C() {
cout << "Constructing C." << endl;
};
virtual ~C() {
cout << "Destructing C." << endl;
}
};
void deallocatorFunc(A *p)
{
cout << "Deallocator function." << endl;
delete p;
};
namespace boost {
template<> class shared_ptr<A> {
private:
shared_ptr<void> _ptr;
public:
shared_ptr(A* p) : _ptr(p, deallocatorFunc)
{
}
};
}
int main( int argc, const char* argv[] )
{
boost::shared_ptr<A> ptrA(new A());
boost::shared_ptr<B> ptrB(new B());
boost::shared_ptr<C> ptrC(new C());
}
输出:
Constructing A. Constructing A. Constructing B. Constructing C. Destructing C. Destructing B. Destructing A. Deallocator function. Destructing A.
注意
如前所述,特化不适用于 A 的派生类!
要实现这一点,您需要更多技巧:
关于c++ - 如何在本地重新定义 boost::shared_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9012557/