1

I am having trouble making forward declarations work with std::unique_ptr. I have read other similar posts on SO and elsewhere online, but either the answers in those posts do not directly address my concern, or I am misinterpreting/misunderstanding the answers. So, in case someone feels that this is a duplicate question (esp. with reference to Is std::unique_ptr<T> required to know the full definition of T?), please clarify how the answers in the original question help my example below, because I tried and could not figure it out.

To illustrate the issues I am running into, I have built a project with the following code files:

//main.cpp
int main(int argv, char* argv[]) { return 0;}

//Composite.h
#pragma once
#include<memory>

class Individual;

class Composite
{
public:
    Composite();
    ~Composite();
private:
    std::unique_ptr<Individual> mInd;
};

//Composite.cpp
#include "Composite.h"

Composite::Composite() {}
Composite::~Composite() {}

//Individual.h
#pragma once
class Individual
{
public:
    Individual();
    ~Individual();
};

//Individual.cpp
#include "Individual.h"

Individual::Individual() {}
Individual::~Individual() {}

I am unable to compile the above project in Visual Studio 2017. Essentially the compiler complains of:

Error C2027: use of undefined type "Individual"

Error C2338: can't delete an incomplete type

Note that neither Composite nor Individual is instantiated, which is on purpose to illustrate the problem. Whatever I found on SO and elsewhere online seems to suggest the above files should compile because:

  1. The compiler needs to know the complete definition of Individual before Composite is instantiated. Since Composite is never instantiated, there should be no compilation errors.
  2. A number of solutions online suggest that defining an empty destructor in the .cpp file (instead of defining it in the header file) should resolve issues related to std::unique_ptr and incomplete types. I have done that in the above files.

So, why the compilation errors?

P.S. I have read the post at Is std::unique_ptr<T> required to know the full definition of T?. There is a table provided in the accepted answer that I cannot make any sense of. The constructor/destructor requirements in that table... does it apply to the owning class or the class for which the std::unique_ptr is constructed? In fact, the third comment to the answer essentially advises to provide some clarification, but the comment was not responded to as far as I can tell.

Thanks in advance to all those who bothered to help.

Community
  • 1
  • 1

0 Answers0