[英]How can I locally redefine boost::shared_ptr?
我有一個函數名為void deallocatorFunc(ClassA *p)
我想使用模板來編寫boost::shared_ptr< ClassA > ptr(new ClassA());
而不是boost::shared_ptr< ClassA > ptr(new ClassA(), deallocatorFunc);
。 我希望它傳播到我的班級及其繼承者。 如何在C ++中做這樣的事情? (我確實需要特殊的析構函數用於該特殊類,而我想保留超簡單的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());
}
輸出:
構造A.構造A.構造B.構造C.破壞C.破壞B.破壞A. Deallocator函數。 破壞A。
注意
如給定的,專業化不適用於A的派生類!
為此,您需要更多的技巧:
namespace boost {
template<typename myclass> class shared_ptr {
};
}
享受您對boost :: shared_ptr的重新定義。 標頭中包含上述代碼的所有內容都將獲取您的 shared_ptr
而不是boost的。
請記住,這將與包含boost本身的代碼不兼容!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.