继承自shared_ptr <void> </void>

时间:2015-03-01 10:29:23

标签: c++ c++11 shared-ptr

我继承自shared_ptr<void>以存储额外的字段length,显示由malloc函数分配的内存长度。
我也将free作为自定义删除功能传递。

// a chunk of memory that will automatically be deleted
struct bytes : public std::shared_ptr<void> {
public:
   unsigned int length;
   bytes(std::nullptr_t) :
       std::shared_ptr<void>(nullptr),
       length(0) { }
   bytes(int len) :
       std::shared_ptr<void>(malloc(len), free),
       length(len) { }
};

// a sample use case
bytes foo(int n){
   if( condition1)
      return nullptr;
   bytes b(100);
   // ....
   fread(b.get(),1,100,file_pointer);
   // ....
   return b;
}

我只是不确定这段代码是否隐藏了错误? (我是c ++ 11的新手。)

1 个答案:

答案 0 :(得分:2)

这是一个非常可怕的想法。它只是std::shared_ptr<std::vector<char>>,但是添加了非常类似于继承非虚拟析构函数的类。

你真的很喜欢编写现有的标准类而不是自己动手。它非常优越。

相关问题