我编写了表示无向图的简单类。我想要一个私有(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/