Can't use std::unique_ptr<T> with T being a forward declaration

hllnll picture hllnll · Feb 7, 2015 · Viewed 9.7k times · Source

Now first, I am aware of the general issues with unique_ptr<> and forward declarations as in Forward declaration with unique_ptr? .

Consider these three files:

A.h

#include <memory>
#include <vector>

class B;

class A
{
public:
    ~A();

private:
    std::unique_ptr<B> m_tilesets;
};

C.cpp

#include "A.h"

class B {

};

A::~A() {

}

main.cpp

#include <memory>

#include "A.h"

int main() {
    std::unique_ptr<A> m_result(new A());
}

Issuing g++ -std=c++11 main.cpp C.cpp yields the following error:

In file included from /usr/include/c++/4.8/memory:81:0,
                 from main.cpp:1:
/usr/include/c++/4.8/bits/unique_ptr.h: In instantiation of ‘void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = B]’:
/usr/include/c++/4.8/bits/unique_ptr.h:184:16:   required from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = B; _Dp = std::default_delete<B>]’
A.h:6:7:   required from here
/usr/include/c++/4.8/bits/unique_ptr.h:65:22: error: invalid application of ‘sizeof’ to incomplete type ‘B’
  static_assert(sizeof(_Tp)>0,

That's true, B is an incomplete type in line 6 of A.h - but that's not where A's destructor is! g++ seems to generate a destructor for A even though I am providing one. A's destructor is in C.cpp line 7 and there B is a perfectly defined type. Why am I getting this error?

Answer

Chris Drew picture Chris Drew · Feb 7, 2015

You also need to put A's constructor in C.cpp:

A.h

#include <memory>
#include <vector>

class B;

class A {
public:
     A();
    ~A();

private:
    std::unique_ptr<B> m_tilesets;
};

C.cpp

#include "A.h"

class B {

};

A::~A() {

}

A::A() {

}

See this answer. The constructor needs access to the complete type as well. This is so that it can call the deleter if an exception is thrown during construction.