2
votes

I write simple class representing undiricted graph. I would like to have a private class member - pointer to dynamically allocated array of sets. Every set in array represent the vertices adjacent with vertex with corresponding array index number. Also there is two constructors: one taken array size(vertex count) as a parameter, second - read it from file. I want to use boost::shared_ptr to manage memory allocated. Boost documentation says:

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

I've created a class member and two constructors:

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

How to init my shared_ptr, for first constructor I use initialization list:

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

Is it proper shared_ptr handling dynamically allocated array initialization? Ang how to init shared_ptr when I receive it's size inside second constructor's body?

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

Can I do better?

2

2 Answers

2
votes

Your shared pointers to arrays look good. In the last constructor you can just assign a value to adj using shared_ptr's constructor or make_shared function ( http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/make_shared.html ):

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

just like you'd do with normal pointers.

2
votes

Since you are using boost, you could consider boost::shared_array.

boost::shared_array<std::set<int>> set_array;

alternatively, since boost 1.53, boost::shared_ptr understands dynamically allocated arrays:

boost::shared_ptr<std::set<int>[]> set_array(new std::set<int>(N));