继承自shared_ptr<void>

inheriting from shared_ptr<void>

本文关键字:lt void gt ptr shared 继承      更新时间:2023-10-16

我从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的新手)。

这真是个糟糕的主意。它只是std::shared_ptr<std::vector<char>>,但添加了一些可怕的东西,比如从具有非虚拟析构函数的类继承。

你真的应该喜欢编写现有的标准类,而不是自己乱折腾。它非常优越。