问题
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.
回答1:
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';
回答2:
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);
回答3:
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);
来源:https://stackoverflow.com/questions/13794447/can-you-allocate-an-array-with-something-equivalent-to-make-shared