C++ shared_ptr 保存动态分配的数组

标签 c++ boost stl shared-ptr

我编写了表示无向图的简单类。我想要一个私有(private)类成员 - 指向动态分配的集合数组的指针。数组中的每个集合表示与对应数组索引号的顶点相邻的顶点。还有两个构造函数:第一个将数组大小(顶点数)作为参数,第二个 - 从文件中读取它。 我想使用 boost::shared_ptr 来管理分配的内存。 Boost 文档说:

Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array

我创建了一个类成员和两个构造函数:

boost::shared_ptr<std::set<int>[]> adj;
...
Graph(unsigned int vertices);
Graph(std::ifstream& inputStream); // read 

如何初始化我的shared_ptr,对于第一个构造函数,我使用初始化列表:

Graph::Graph(unsigned int vertices)
        :adj(new std::set<int>[vertices]),
        vertexCount(vertices){
}

shared_ptr 处理动态分配的数组初始化是否正确? 当我收到第二个构造函数体内的shared_ptr的大小时,如何初始化shared_ptr?

Graph::Graph(std::ifstream& inputStream){
        inputStream >> std::dec >> vertexCount; // read vertex count from file
        // how to init shared_ptr with vertexCount array size?            
        }

我能做得更好吗?

最佳答案

您的共享数组指针看起来不错。在最后一个构造函数中,您可以使用shared_ptr的构造函数或make_shared函数(http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/make_shared.html)为adj赋值:

adj = boost::shared_ptr<std::set<int>[]>(new std::set<int>[vertexCount]);
//or
adj = boost::make_shared(new std::set<int>[vertexCount]);

就像使用普通指针一样。

关于C++ shared_ptr 保存动态分配的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17385125/

相关文章:

c++ - 是否可以让一个 vector 指向其他 vector 的子集?

c++ - 对具有不可复制值的 STL 容器使用 boost 序列化时出现编译错误

C++11:返回一个数组

c++ - boost::variant 几何算法断言失败

c++ - 如果迭代器未因插入而失效,则使用 std::find 和 C::insert() 线程安全

c++ - 隐藏容器的类的更好接口(interface)

c++ - 类型应该在面向数据的设计中包含方法吗?

c++ - c++ STL中是否有任何三态类型?

c++ - boost::asio 服务器多进程

c++ - 无法针对 OS X 上的 Boost.log 进行编译