c++ - 如何在本地重新定义 boost::shared_ptr?

标签 c++ templates pointers boost typedef

我有一个函数名为 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 的派生类!

要实现这一点,您需要更多技巧:

Template specialization based on inherit class

关于c++ - 如何在本地重新定义 boost::shared_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9012557/

相关文章:

c++ - 如何从循环中构建 boost::spirit 规则?

c++ - 在 C 中包装 C++ 成员函数 - Visual Studio 2013 模板问题

c++ - 使用 typedef、多维数组和指针时出现编译器错误

cygwin char指针和char地址--------比较两个scanf程序

C++ const 通过指针改变,或者是吗?

c++ - 在字符串C++中的字符之间添加空格

c++ - QSortFilterProxyModel::filterAcceptRows 是否可自定义以接受仿函数?

c++ - 使用省略号的回退函数 : can we force the size of the parameters pack?

c++ - 我在模板类中有多个 * 运算符的重载。为什么按不同的顺序放置声明会得到不同的结果?

c++ - 更多类的模板化律师-客户习语