Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaration with unique_ptr? [duplicate]

I have found it useful to use forward declaration of classes in combination with std::unique_ptr as in the code below. It compiles and works with GCC, but the whole thing seem kind of strange, and I wonder if this is standard behaviour (i.e. required by the standard)? Since B isn't a complete type when I declare the unique_ptr.

A.hpp

#include <memory>  class B;  class A {     std::unique_ptr<B> myptr;     // B::~B() can't be seen from here public:     ~A(); }; 

A.cpp

#include "B.hpp" //B.hpp has to be included, otherwise it doesn't work.  A::~A() = default; // without this line, it won't compile  // however, any destructor definiton will do. 

I suspect this has to do with the destructor (and therefore the need to call the destructor of unique_ptr<B>) is defined in a specific compilation unit (A.cpp).

like image 626
Zyx 2000 Avatar asked Nov 16 '12 10:11

Zyx 2000


People also ask

Can you copy unique_ptr?

A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.

What does unique_ptr mean in C++?

(since C++11) std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

Do you need to delete a unique_ptr?

An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.

What happens when unique_ptr goes out of scope?

unique_ptr. An​ unique_ptr has exclusive ownership of the object it points to and ​will destroy the object when the pointer goes out of scope.


1 Answers

It's explicitly legal. The rule is that the types used to instantiate a template in the standard library must be complete, unless otherwise specified. In the case of unique_ptr, §20.7.1/5 says “[...] The template parameter T of unique_ptr may be an incomplete type.”

There are certain operations on the pointer which require a complete type; in particular, when the object will actually be destructed (at least with the default deleter). In your example, for example, if A::~A() were inline, this might cause problems. (Note that if you don't declare the destructor yourself, it will be inline. Which partially defeats the purpose of using std::unique_ptr.)

like image 79
James Kanze Avatar answered Sep 24 '22 14:09

James Kanze