mercredi 5 avril 2017

include a class that has std::unique_ptr

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.

Aucun commentaire:

Enregistrer un commentaire