I'm inheriting from shared_ptr<void>
to store an extra filed length
that shows the length of memory allocated by malloc
function.
I'm also passing free
as a custom delete function.
// 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 ? (I'm new to 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.
You should really favour composing existing Standard classes rather than crapping around on your own. It is vastly superior.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.