你可以分配一个相当于make_shared的数组吗? [英] Can you allocate an array with something equivalent to make_shared?

查看:3414
本文介绍了你可以分配一个相当于make_shared的数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  buffer = new char [64]; 
buffer = std :: make_shared< char>(char [64]); ???可以使用 make_shared<>()为数组分配内存。 / code>?



我可以做: buffer = std :: make_shared< char>(new char [64]); / code>



但是这还涉及调用new,这是因为我理解 make_shared 更安全,更多效率。

解决方案

make_shared的意义是将托管对象合并到共享指针的控制块中,



因为你在处理C ++ 11,或许使用C ++ 11数组才能满足你的目标?

  #include< memory> 
#include< array>
int main()
{
auto buffer = std :: make_shared< std :: array< char,64&
}

注意,你不能像指针一样使用共享指针你会从新的[],因为 std :: shared_ptr (不同于例如 std :: unique_ptr 不提供 operator [] 。您必须取消引用它:(* buffer)[n] ='a';


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.

解决方案

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

这篇关于你可以分配一个相当于make_shared的数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆