Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

c++ - Unique_ptr and forward declaration

Say I have two classes:

"Foo.h"

#pragma once    
class Foo
{
public:
    Foo()
    {

    };

    ~Foo()
    {

    };
};

"A.h"

#pragma once
#include <memory>

class Foo;

class A
{
public:
    A(){};
    ~A(){};

    std::unique_ptr<Foo> foo;
};

A holds a unique_ptr of Foo. I didn't want to include Foo in "A.h", so I forward declared it. By just forward declaring the class Foo in "A.h", I get a compile time error:

error C2027: use of undefined type 'Foo'
error C2338: can't delete an incomplete type  

So I was following this article on how to avoid this error and moved A's destructor in it's own .cpp file where I also include Foo:

"A.cpp"

#include "A.h"

#include "Foo.h"

A::A()
{

}

A::~A()
{

}

After implementing the destructor of A in "A.cpp", I'm able to compile the program, because the class Foo is known in "A.cpp". This seems logical, because unique_ptr needs the complete type to call it's destructor. But to my surprise, after commenting out the constructor of A (in "A.h" as well as "A.cpp"), I get the same error. How is this possible? Why does the compiler complain about beeing not able to call Foo's destructor when A has no constructor?

EDIT: I uploaded the 4 files so you can test the program. I'm using MSVC++ of Visual Studio 2013.

http://www.filedropper.com/test_61

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The constructor needs access to the deleter in just the same way the destructor does: exception safety requires that the constructor be able to roll-back initialisation of all the members in the case that your constructor's body throws:

[C++14: 12.6.2/10]: In a non-delegating constructor, the destructor for each potentially constructed subobject of class type is potentially invoked (12.4). [ Note: This provision ensures that destructors can be called for fully-constructed sub-objects in case an exception is thrown (15.2). —end note ]

Related:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...