Possible error in the implementation of unique_ptr

I tried to use a unique_ptr class element with a forward declaration. How do numerous sources report, for example, forward a declaration using unique_ptr? should be enough to declare a non-built-in destructor, but this does not seem to apply to VS2013 and GCC 5.3.1. I have not tested other compilers.

Example:

#include <memory> class B; class A { public: //A(); ~A(); private: std::unique_ptr<B> b; }; //class B { }; int main() { A a; } 

I can compile this code only after uncommenting the ctor declaration or class B declaration. Otherwise on VS2013 I get an error

 error C2338: can't delete an incomplete type 

on GCC error:

 In file included from /usr/local/include/c++/5.3.0/memory:81:0, from main.cpp:1: /usr/local/include/c++/5.3.0/bits/unique_ptr.h: In instantiation of 'void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = B]': /usr/local/include/c++/5.3.0/bits/unique_ptr.h:236:17: required from 'std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = B; _Dp = std::default_delete<B>]' main.cpp:5:7: required from here /usr/local/include/c++/5.3.0/bits/unique_ptr.h:74:22: error: invalid application of 'sizeof' to incomplete type 'B' static_assert(sizeof(_Tp)>0, ^ 

Why is this?

+5
source share
1 answer

The class A destructor must know the definition of class B. The prospective declaration of class B is fine, since the implementation file of the constructor / destructor A knows the definition of class B. If your implementation is (implicitly) in the header file, then you need the definition of B in the header file. You can explore Pimpl from Herb Sutter.

+2
source

Source: https://habr.com/ru/post/1245165/


All Articles