make_shared和allocate_shared在boost中的用法? [英] usage of make_shared and allocate_shared in boost?

查看:158
本文介绍了make_shared和allocate_shared在boost中的用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不了解有关如何使用make_sharedallocate_shared初始化共享数组和指针的boost文档:

I'm not able to understand the boost documentation on how to use make_shared and allocate_shared to initialize shared arrays and pointers:

shared_ptr<int> p_int(new int); // OK
shared_ptr<int> p_int2 = make_shared<int>(); // OK
shared_ptr<int> p_int3 = allocate_shared(int);  // ??


shared_array<int> sh_arr(new int[30]); // OK
shared_array<int> sh_arr2 = make_shared<int[]>(30); // ??
shared_array<int> sh_arr3 = allocate_shared<int[]>(30); // ??

我正在尝试学习正确的语法来初始化上面注释为// ??

I'm trying to learn the correct syntax to initialize the above variables commented as // ??

推荐答案

allocate_shared的用法与make_shared相似,只是将分配器作为第一个参数传递.

allocate_shared is used just like make_shared, except that you pass an allocator as the first argument.

boost::shared_ptr<int> p_int(new int);
boost::shared_ptr<int> p_int2 = boost::make_shared<int>();

MyAllocator<int> alloc;
boost::shared_ptr<int> p_int3 = boost::allocate_shared<int>(alloc);

boost::shared_array没有make函数,因此唯一的方法是手动分配内存:

There is no make function for boost::shared_array, so the only way to make one is allocating the memory manually:

boost::shared_array<int> sh_arr(new int[30]);

但是boost::make_shared等支持数组类型-未知大小之一,或固定大小之一-在两种情况下均返回boost::shared_ptr:

But boost::make_shared etc. support array types - either one of unknown size, or one of fixed size - in both cases a boost::shared_ptr is returned:

boost::shared_ptr<int[]> sh_arr2 = boost::make_shared<int[]>(30);
boost::shared_ptr<int[30]> sh_arr3 = boost::make_shared<int[30]>();

请注意,std::shared_ptr目前不支持数组.

Note that std::shared_ptr does not support arrays at this time.

这篇关于make_shared和allocate_shared在boost中的用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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