vendredi 10 février 2023

Why unique_ptr requires complete type in constructor?

From Is std::unique_ptr required to know the full definition of T?, I know that if a class A has a member unique_ptr<T>, then T shall be a complete type in destructor ~A(). However, I came across a situation that the constructor A() also requires complete type of T, see code below:

// a.h -------------------------------
#pragma once
#include <memory>
struct B;
struct A {
  A(); // <---
  ~A();
  std::unique_ptr<B> ptr;
};

// a.cpp -------------------------------
#include "a.h"
struct B {};
A::A() = default; // <---
A::~A() = default;

// main.cpp -------------------------------
#include "a.h"
int main() {A a;}

If the definition of constructor A::A() is moved to the header a.h, the compiler will complain error: invalid application of ‘sizeof’ to incomplete type ‘B’. Why is this happening? Is there any reference material about this?

BTW, I'm using gcc-7.5.0 on Ubuntu 18.04, with c++17 enabled.

Aucun commentaire:

Enregistrer un commentaire