5

I created a tiny test case for std::unique<B> with incomplete type B.

Test.h

#pragma once
#include <memory>
class B;   //<--- compile error here
class Test{
    std::unique_ptr<B> bPtr;   
    //#1 need to move destructor's implementation to .cpp
    public: ~Test();
};

Test.cpp

#include "Test.h"
class B{};
Test::~Test(){}  //move here because it need complete type of B

main.cpp

#include <iostream>
#include "Test.h"
using namespace std;
int main(){
   Test test;
   return 0;
}

I got this error:-

/usr/include/c++/4.8.2/bits/unique_ptr.h:65:22: error: invalid application of 'sizeof' to incomplete type 'B'

As far as I understand, the compiler tells me that B is an incomplete type (in main.cpp), so it can't delete B properly.

However, in my design, I want main.cpp to not have complete type of B.
Very roughly speaking, it is a pimpl.

Is there a good workaround?

Here is some similar questions, but none suggest a clean workaround.

Is std::unique_ptr not a right tool?
Should I create my own unique_ptr? I may use #3 as a guide.

Edit:

Kerrek SB has practically solved all problems in the code. Thank a lot!

The remaining question is that :-
Should I create my own unique_ptr to remove this restriction?
Is it possible? - I guess it is possible, and I am trying to code it now.

Community
  • 1
  • 1
javaLover
  • 6,347
  • 2
  • 22
  • 67
  • 4
    The constructor(s) need to move to the .cpp file, too. – Kerrek SB Apr 05 '17 at 11:09
  • 2
    @Kerrek SB Oh no! Shameful me. Many thank. .... adding an empty constructor (and implement to .cpp) make it compile .... I will test it more. ..... After testing in my complex program, it works! Thank! – javaLover Apr 05 '17 at 11:12

0 Answers0