继承自shared_ptr<void>
inheriting from shared_ptr<void>
我从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>>
,但添加了一些可怕的东西,比如从具有非虚拟析构函数的类继承。
你真的应该喜欢编写现有的标准类,而不是自己乱折腾。它非常优越。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 在c++类上调用void函数
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 在派生函数中指定void*参数
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- C++为什么尽管我调用了void函数,它却不起作用
- 如何从void函数输出字符串
- 我应该使用什么来代替void作为变体中的替代类型之一
- 奇怪的结构&GCC&clang(void*返回类型)
- 呼叫运营商<<临时
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 引用一个已擦除类型(void*)的指针
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何将指针从一个void函数传递到另一个C++
- <<操作员在下面的行中工作
- 为什么我在使用void函数时得到错误代码C2276
- void*到驱动程序中的UnicodeString