std::shared_ptr传递删除器

std::shared_ptr passing the deletor

本文关键字:删除 ptr shared std      更新时间:2023-10-16

我有这段代码:

// util.h
#include <memory>
template <class T>
class ArrayDeleter {
public:
    void operator () (T* d) const
    { delete [] d; }
};
std::shared_ptr<char, ArrayDeleter<char> > V8StringToChar(v8::Handle<v8::String> str);
std::shared_ptr<char, ArrayDeleter<char> > V8StringToChar(v8::Local<v8::Value> val);

它给了我错误:

 c:Program Files (x86)Microsoft Visual Studio 10.0VCincludememory
  (1418) : see declaration of 'std::tr1::shared_ptr'c:cefappjs_finalappjssrcincludesutil.h(27): 
error C2977: 'std::tr1::shared_ptr' : too many template arguments 
 [C:CEFappjs_finalappjsbuildappjs.vcxproj]

unique_ptr不同,删除器不是类模板参数。删除程序与使用计数一起存储在单独的对象中,因此可以使用类型擦除使指针对象本身与删除程序类型无关。

有一些构造函数模板允许您使用任何合适的函子类型初始化指针。所以你的函数很简单

std::shared_ptr<char> V8StringToChar(Whatever);

他们将使用合适的删除器创建指针

return std::shared_ptr<char>(array, ArrayDeleter<char>());