Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr instantiation with argument that is not defined yet doesn't lead to error

Tags:

c++

#include <memory>
class Data;
std::unique_ptr<Data> p;
//class Data{}; // not working without this
int main(){}

Compilation of this code with g++-5 gives such error:

invalid application of ‘sizeof’ to incomplete type ‘Data’

Can somebody explain why if I uncomment 4th line compilation will be successful? As I understand in 3rd line compiler hasn't full information about type Data. We have only forward declaration in this line. Real declaration occures in 4th line.

like image 219
poljak181 Avatar asked Jan 29 '23 03:01

poljak181


2 Answers

Target type of unique_ptr type may be incomplete at the point of template instantiation, but must be complete at the point when unique_ptr may try to dispose of the stored pointer because it is a requirement of default_delete that will be invoked. If you are using custom deleter then target type may be still incomplete.

like image 137
user7860670 Avatar answered Feb 06 '23 16:02

user7860670


Your guess is correct. At the 3rd line compiler only knows that this type exists. You forward-declared it. unique_ptr is defined in such a way to give semantics similar to the regular pointer. In 2nd line you promise compiler to actually define the class when it's really needed, and compiler indeed needs the definition of Data class to call destructor on Data in p.

The sizeof error is a common way to "force" complete type definition at the certain point (in this case to prevent UB from calling delete on the incomplete type in p destructor).

like image 25
Dan M. Avatar answered Feb 06 '23 16:02

Dan M.