3

It is quite common to have forward declarations in order to avoid cyclic header file dependencies, or to implement pimpl, then one might end up with code like:

class A;

class B
{
  A * a;
};

When one tries to replace this with a unique_ptr:

class A;

class B
{
  std::unique_ptr<A> a;
};

the compiler complains. What is the best practice to get this working?

g24l
  • 3,055
  • 15
  • 28

1 Answers1

2

One needs to declare the destructor of the enclosing class B, and set this to default in the source file, such that the unique_ptr does not forcibly inline its own default deleter.

class B
{
  public:
  ~B();
  private:
  std::unique_ptr<A> a;
};

and in the source file

#include <A.h>
... do stuff with ( a )
B::~B() = default;

Should do the job.

g24l
  • 3,055
  • 15
  • 28