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.
- C++ Pimpl Idiom Imcomplete Type using std::unique_ptr tells to move destructor to
.cpp
(#1
) - std::unique_ptr with an incomplete type won't compile shows an ugly workaround by encapsulating
std::unique_ptr<B>
with non-template class. Then, manually move the destructor of the encapsulator to.cpp
. (#2
) - std::unique_ptr<T> incomplete type error suggest to provide custom deleter (function). (
#3
)
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.