Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you allocate an array with something equivalent to make_shared?

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.

like image 717
Josh Elias Avatar asked Dec 10 '12 03:12

Josh Elias


People also ask

Why is Make_shared 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.

What is Make_shared in C++?

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.

Does Make_shared throw?

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.


1 Answers

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';

like image 168
Cubbi Avatar answered Sep 18 '22 13:09

Cubbi