2

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?

vard
  • 2,142
  • 4
  • 30
  • 40

2 Answers2

2

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

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));
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • I just learned that shared_ptr learned arrays. With that what would be the benefit of using shared_array? – Balog Pal Jun 29 '13 at 22:35
  • I just read up the dox (as first I thought it cant't work :), it implies full support, and thinking after-the-fact with type_traits it's really not hard to unite them. As make_shared return shared_ptr with [] type I expect it to just know the deal without custom deleter. – Balog Pal Jun 29 '13 at 22:41
  • @BalogPal Yes, I checked too, its behaviour seems quite different to that of `std::shared_ptr` in this respect. I am deleting this. – juanchopanza Jun 29 '13 at 22:44