Vince
Vince

Reputation: 4439

C++ / boost : declaring an encapsulated shared_array

I recently started to use smart pointers. If I am correct, smart pointers are declared:

shared_array<double> a(new double[n]);

But how do we do if a is encapsulated in a class ? For the moment I am doing as follow, but that seems super ugly:

header file:

class Foo {
public:
    Foo(int size);
    shared_array<double> _a;
};

source file

Foo::Foo(int n){
    shared_array<double> p (new double[n]);
    _a = p;
}

Upvotes: 1

Views: 232

Answers (1)

juanchopanza
juanchopanza

Reputation: 227588

You can use the constructor initialization list:

Foo::Foo(int n) : _a(new double[n]) {}

In case you need to set the managed array in the constructor's body, then

Foo::Foo()
{
  int n = someCalculation();
  _a.reset(new double[n]);
}

Upvotes: 2

Related Questions