buffer = new char[64]; buffer = std::make_shared<char>(char[64]); ???
Can you allocate memory to an array using make_shared<>()
?
I could do: buffer = std::make_shared<char>( new char[64] );
But that still involves calling new, it's to my understanding make_shared
is safer and more efficient.
One reason is because make_shared allocates the reference count together with the object to be managed in the same block of memory. OK, I got the point. This is of course more efficient than two separate allocation operations.
std::make_sharedAllocates and constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr<T> that owns and stores a pointer to it (with a use count of 1). This function uses ::new to allocate storage for the object.
So, if you throw exception from your class' constructor, then std::make_shared will throw it too. Besides exceptions thrown from constructor, std::make_shared could throw std::bad_alloc exception on its own.
The point of make_shared is to incorporate the managed object into the control block of the shared pointer,
Since you're dealing with C++11, perhaps using a C++11 array would satisfy your goals?
#include <memory> #include <array> int main() { auto buffer = std::make_shared<std::array<char, 64>>(); }
Note that you can't use a shared pointer the same way as a pointer you'd get from new[], because std::shared_ptr
(unlike std::unique_ptr
, for example) does not provide operator[]
. You'd have to dereference it: (*buffer)[n] = 'a';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With