简体   繁体   中英

How to create dynamic size buffer with std::make_shared

I want to optimize next method

auto MakeBuffer(size_t size)
{
    return std::shared_ptr<uint8_t>{new uint8_t[size], std::default_delete<uint8_t[]>()};
}

As you can see buffer is created in two stages:

  • memory is allocated for the buffer
  • shared_ptr is created (and memory is allocated for a controlling object under the hood)

In general case we can avoid double allocation by using std::make_shared. But how can I do it for dynamic size buffer? std::allocate_shared isn't a solution (if I understand correctly) as a custom allocator is designed to create only object not a controlling block

Edit. Fixed bug in buffer cleaning

If you can use boost instead:

return boost::make_shared<uint8_t[]>(size);

There appears to be a proposal to add the extension to the standard, but I don't know what became of it. Perhaps it will be part of a future standard. Update: It's in C++20.

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.

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