Unique_ptr和forward声明 [英] Unique_ptr and forward declaration

查看:217
本文介绍了Unique_ptr和forward声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个课程:

Foo.h

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

    };

    ~Foo()
    {

    };
};

Ah

#pragma once
#include <memory>

class Foo;

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

    std::unique_ptr<Foo> foo;
};

A持有 unique_ptr $ c> Foo 。我不想在A.h中包含 Foo ,所以我转发声明它。通过在Ah中声明类 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  

因此,我关注了这个文章如何避免这个错误,并移动A的析构函数在它自己的.cpp文件,其中我也包括Foo:

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 p>

"A.cpp"

#include "A.h"

#include "Foo.h"

A::A()
{

}

A::~A()
{

}

在A.cpp中实现A的析构函数后,因为类Foo在A.cpp中是已知的。这似乎是合乎逻辑的,因为unique_ptr需要完整的类型来调用它的析构函数。但令我惊讶的是,在注释掉A的构造函数(在A.h以及A.cpp)后,我得到相同的错误。这怎么可能?为什么编译器会抱怨当A没有构造函数时beeing不能调用Foo的析构函数?

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?

编辑:
我上传了4个文件,程序。
我使用Visual Studio 2013的MSVC ++。

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

推荐答案

构造函数需要访问删除器,方法与析构函数:异常安全性要求构造函数能够在构造函数体抛出的情况下回滚所有成员的初始化:

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]:在非委托构造函数中,潜在构造的类类型的子对象的析构函数可能被调用(12.4) 。 [注意:此条款确保在抛出异常(15.2)时可以为完全构造的子对象调用析构函数。 -end note]

[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 ]

相关:

  • http://stackoverflow.com/a/26995534/560648

这篇关于Unique_ptr和forward声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆