c++unique-ptrforward-declarationincomplete-type

C++ another unique_ptr incomplete type question


Have looked at various similar questions here but still can't figure out why the following code does not compile:

// these three are defined somewhere
class A;
std::unique_ptr<A> make_a(); 
void take_a(std::unique_ptr<A>&&);

int main(){
   take_a(make_a()); // this fails
   return 0;
}

According to this:

If the default deleter is used, T must be complete at the point in code where the deleter is invoked, which happens in the destructor, move assignment operator, and reset member function of std::unique_ptr.

As far as I understand, none of these (destructor, move assignment operator, nor reset member function) happens in main.

So why does compiler needs the definition of A here?


Solution

  • Since main has a unique_ptr within its scope, realistically it would need to know how to delete the object it holds.

    It's possible that take_a doesn't actually take ownership of the object, thus main would need to delete.