Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pimpl with unique_ptr : Why do I have to move definition of constructor of interface to ".cpp"?

The code would work file as long as I don't move the definition of constructor (of B) to the header B.h.

B.h

class Imp;  //<--- error here
class B{
    public:
    std::unique_ptr<Imp> imp;
    B();     //<--- move definition to here will compile error
    ~B();
    //// .... other functions ....
};

B.cpp

#include "B.h"
#include "Imp.h"
B::B(){ }
~B::B(){ }

Imp.h

class Imp{};

Main.cpp (compile me)

#include "B.h"

Error: deletion of pointer to incomplete type
Error: use of undefined type 'Imp' C2027

I can somehow understand that the destructor must be moved to .cpp, because destructure of Imp might be called :-

delete pointer-of-Imp;  //something like this

However, I don't understand why the rule also covers constructor (question).

I have read :-

  • Deletion of pointer to incomplete type and smart pointers
    describes reason why destructor need to be in .cpp.
  • std::unique_ptr with an incomplete type won't compile
    warns about the default destructor.
like image 314
javaLover Avatar asked Feb 23 '17 13:02

javaLover


1 Answers

The constructor needs to destroy the class members, in the case that it exits by exception.

I don't think that making the constructor noexcept would help, though maybe it should.

like image 85
Potatoswatter Avatar answered Oct 13 '22 22:10

Potatoswatter