How to forward a boost smart ptr ad?

This code does not compile:

namespace boost { template<class T> class scoped_ptr; } namespace FooNamespace { class FooClass { boost::scoped_ptr<FooType> foo; }; } 

g ++ says: error: field 'foo has incomplete type

I thought everything would be alright, since I copied the scoped_ptr declaration from the actual Boost header file ... What did I screw?

Note: the problem is not FooType . I tried replacing its int no avail ...

Thanks!

+5
source share
3 answers

Variable declarations do not work if the size of the forward declared type must be known. Since you are embedding an instance of boost::scoped_ptr<T> in FooClass , the size of this type must be known.

Instead, you can insert a pointer, but this is likely to cause the scoped_ptr<T> to hit the target in the first place. However, he would compile:

 class FooClass { boost::scoped_ptr<FooType> *foo; }; 
+6
source

There are restrictions on what you can do with an incomplete type (i.e. a type that has been declared but not defined); one thing you cannot do is define a variable of this type. This is because the size must be known, in this case, to develop a layout of member variables inside the object.

Things you can do include using a pointer or a type reference (if you are not looking for it), declaring a function with a type as an argument or return value, and declaring variables of a static or non-member type.

+6
source

For boost::scoped_ptr your boost::scoped_ptr type must be completed when defining the FooClass destructor:

 //header file hpp class FooType; class FooClass { FooClass(); ~FooClass(); boost::scoped_ptr<FooType> foo; }; //source file cpp #inlcude "FooClass.hpp" #inlcude "FooType.hpp" FooClass::FooClass() {} FooClass::~FooClass() {} 
0
source

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


All Articles