简体   繁体   English

从shared_ptr继承<void>

[英]inheriting from shared_ptr<void>

I'm inheriting from shared_ptr<void> to store an extra filed length that shows the length of memory allocated by malloc function. 我从shared_ptr<void>继承来存储额外的文件length ,该文件length显示了malloc函数分配的malloc长度。
I'm also passing free as a custom delete function. 我还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;
}

I'm just not sure if this code has hidden bugs or not ? 我只是不确定这段代码是否有隐藏的bug? (I'm new to c++11). (我是c ++ 11的新手)。

This is a truly terrible idea. 这是一个真正可怕的想法。 It's just std::shared_ptr<std::vector<char>> , but with added awful like inheriting from a class with a non-virtual destructor. 它只是std::shared_ptr<std::vector<char>> ,但添加了可怕的效果,例如从具有非虚拟析构函数的类继承。

You should really favour composing existing Standard classes rather than crapping around on your own. 您应该真正喜欢组成现有的Standard类,而不是自己随意包装。 It is vastly superior. 它非常优越。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM