Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...