views:

75

answers:

4

I have a class with an array of scoped pointers to objects which do NOT have a default constructor.

The only way I've found to "initialise" them is using swap() like this:

class Bar {
  Bar(char * message) {};
}

class Foo 
{
  boost::scoped_ptr<Bar> arr[2];

  Foo()
  {
    arr[0].swap(boost::scoped_ptr<Bar>( new Bar("ABC") ));
    arr[1].swap(boost::scoped_ptr<Bar>( new Bar("DEF") ));
  };
}

This feels a little verbose and clunky. Have I missed a smarter way of doing it?

+1  A: 

What about using a typedef?

typedef boost::scoped_ptr<Bar> TBarPtr;
arr[0].swap(TBarPtr(new Bar("ABC"));
Lars
+3  A: 

The biggest problem is that there is no way to initialize an array using the member initializer list here. You might want to use a specialized pointer container like ptr_vector instead:

struct Foo {
    boost::ptr_vector<Bar> bars;    
    X() : bars(boost::assign::ptr_list_of<Bar>("ABC")("CDE")) {}
};
Georg Fritzsche
+1  A: 

One solution: use boost::ptr_vector instead of an array.

You could also use std::vector<scoped_ptr> and fill the array using push_back. Edit: I think this won't work with scoped_ptr.

Mark Ransom
+6  A: 
arr[0].reset(new Bar("ABC"));
arr[1].reset(new Bar("DEF"));
BlueRaja - Danny Pflughoeft
As expected, I'd missed the obvious way. Thanks!
Roddy