c++ - 在boost中使用make_shared和allocate_shared?

标签 c++ boost

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

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); // ??

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

最佳答案

allocate_shared 的使用方式与 make_shared 相同,只是您将分配器作为第一个参数传递。

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 函数,所以制作一个的唯一方法是手动分配内存:

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

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

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 目前支持数组。

关于c++ - 在boost中使用make_shared和allocate_shared?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28929483/

相关文章:

c++ - 希望线程在父级退出时不死 - linux

c++ - cout打印不准确的结果,而printf打印准确的结果

c++ - 交换两个 boost::adjacency_list 图,类似于 std::swap

c++ - boost::accumulator::tag::mean 的返回类型

c++ - 自然算术 C++ 总是返回 1

c++ - MFC C++ - 在没有命令的情况下在 ProcessShellCommand() 上崩溃

c++ - 可以通过其他获取操作获取负载重新排序吗? cppreference 说只有非原子的和宽松的通过 acquire 排序

c++ - 如何使用 boost lib 编译 c++ 代码?在 Ubuntu 上

c++ - 更改命名空间以自定义 boost xml 的标签名称后的反序列化问题

c++ - 重载 boost::lexical_cast 函数