43
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.

2
  • 3
    std::vector<char> buffer(64); Dec 11, 2012 at 0:36
  • No, you can't do "std::make_shared<char>( new char[64] );".
    – ABCD
    Apr 22, 2019 at 1:43

4 Answers 4

35

Do you need the allocated memory to be shared? You can use a std::unique_ptr instead and the std::make_unique available on C++14:

auto buffer = std::make_unique<char[]>(64);

There will be a std::make_shared version available in C++20:

auto buffer = std::make_shared<char[]>(64);
5
  • 2
    even if you do want it shared, make_unique will work std::shared_ptr<char[]> b; b = std::make_unique<char[]>(25);
    – Thomas
    Oct 6, 2020 at 21:36
  • 1
    @Thomas Yes, make_unique will work just fine. But initializing a shared_ptr that way will cost you an extra memory allocation. Which can be avoided when using make_shared.
    – Paul Groke
    Nov 18, 2020 at 18:30
  • @PaulGroke True, but for completeness sake I'll add that that saved allocation comes with a slight risk weak_ptr, make_shared and memory deallocation
    – Thomas
    Nov 18, 2020 at 18:43
  • @Thomas Is it fine to remove the semicolon and have it all in one statement? The comment here seems to indicate that it is fine, but wanted to confirm.
    – Venryx
    Jul 28 at 12:42
  • 1
    yes, it can be written as std::shared_ptr<char[]> b = std::make_unique<char[]>(25);
    – Thomas
    Jul 29 at 15:02
30

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

9
  • 1
    I can't specify the size of the array at compile time though?
    – Josh Elias
    Dec 10, 2012 at 3:33
  • 3
    @JoshElias You sure can at compile time. Do you mean runtime? That would require your own class that takes array size as a constructor argument, since make_shared<T> forwards its runtime arguments to the constructor of T. Or just make a shared vector.
    – Cubbi
    Dec 10, 2012 at 14:18
  • 1
    Yes sorry I did mean runtime. Ah..That's an excellent idea, thank you for educating a noob!
    – Josh Elias
    Dec 10, 2012 at 16:07
  • 3
    Upvoted for insight, but you should know that make_shared isn't just for premature optimization; it's also for exception-safety. std::shared_ptr<T>(new T) is a red flag because it leaks the new T if shared_ptr's constructor happens to throw a bad_alloc exception. Nov 5, 2014 at 0:21
  • 1
    @PeteC we're both right, in that the problem case is subtler than my terse comment had implied. The problem is with an expression such as foo(sh_ptr(new T), sh_ptr(new U)); — where there's no sequence point between the calls to sh_ptr's constructor, so a valid order of construction is new U, new T, sh_ptr(<ptr to T>), sh_ptr(<ptr to U>). If either of the middle two calls throw, then new U is leaked. herbsutter.com/gotw/_102 Jun 29, 2015 at 17:21
7

How about this?

template<typename T>
inline std::shared_ptr<T> MakeArray(int size)
{
    return std::shared_ptr<T>( new T[size], []( T *p ){ delete [] p; } );
}

auto  buffer = new char[64];
auto  buffer = MakeArray<char>(64);
3
  • 3
    There is a difference between creating new shared_ptr and using make_shared, the later has 1 less atomic operation and it's preferred whenever possible.
    – SagiLow
    Oct 23, 2017 at 9:15
  • 1
    This method also doesn't allocate the reference count with the array, so it costs two calls into the memory manager.
    – seattlecpp
    Dec 6, 2019 at 0:29
  • 1
    Considering C++20 is around the corner and this "polyfill" allows us to write code very close to what it will look like once your compiler of choice supports C++20's make_shared<T[]>(size_t), the overhead will be greatly outweighed by more clean robust future-proof code. If you rename the template to something like "make_shared_array" it's obvious what the intent was when you come back to your code next year to upgrade it ;-) This helps greatly working with variable structure buffers, as many system calls require. The other variable array methods generate blocking cast warnings=errors.
    – Tony Wall
    Apr 17, 2020 at 13:35
0

The most efficient way is to use the make_shared() overload below, which is available in Boost and C++20.

template< class T >
shared_ptr<T> make_shared( std::size_t N );

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.