C ++类前向声明​​的缺点? [英] C++ Class forward declaration drawbacks?

查看:243
本文介绍了C ++类前向声明​​的缺点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的软件中使用类的前向声明,所以我可以有typedefs

并在类完整声明中使用它们。

I want to use forward declaration of a class in my software, so I can have typedefs
and use them inside the class full declaration.

Smth像这样:

class myclass;
typedef boost::shared_ptr<myclass> pmyclass;
typedef std::list<pmyclass > myclasslist;

class myclass : public baseclass
{
private:        // private member declarations
        __fastcall myclass();

public:         // public member declarations
        __fastcall myclass(myclass *Parent)
            : mEntry(new myclass2())
          {
            this->mParent = Parent;
          }
        const myclass *mParent;
        myclasslist mChildren;
        boost::scoped_ptr<myclass2> mEntry;
};

所以我的问题是:
这个方法有什么缺点吗?我回想起一些关于前瞻性声明的析构问题的讨论,但我没有得到所有的东西。

或者有任何其他选项来实现这样的东西吗?

so my question is: are there any drawbacks in this method? I recall some discussion on destructor issues with forward declaration but I did not get everything out of there.
or is there any other option to implement something like this?

谢谢。

编辑:
我发现我的讨论:这里

推荐答案

主要的缺点是一切。转发声明是保存编译时间的一种妥协,让您在对象之间具有循环依赖性。但是,成本是你只能使用类型作为引用,不能对这些引用做任何事情。这意味着,没有继承,没有传递它作为值,没有使用任何嵌套类型或typedef在那个类,等...这些都是很大的缺点。

The main drawback is everything. Forward declarations are a compromise to save compilation time and let you have cyclic dependencies between objects. However, the cost is you can only use the type as references and can't do anything with those references. That means, no inheritance, no passing it as a value, no using any nested type or typedef in that class, etc... Those are all big drawbacks.

具体的销毁问题你正在谈论的是,如果你只转发声明一个类型,并发生只在模块中删除它,行为是未定义的,不会抛出错误。

The specific destruction problem you are talking about is if you only forward declare a type and happen to only delete it in the module, the behavior is undefined and no error will be thrown.

例如:

class A;

struct C 
{
    F(A* a)
    {
        delete a;  // OUCH!
    }
}

Microsoft C ++ 2008不会调用任何析构函数以下警告:

Microsoft C++ 2008 won't call any destructor and throw the following warning:

warning C4150: deletion of pointer to incomplete type 'A'; no destructor called
             : see declaration of 'A'

如果您将警告视为错误,这不应该是一个问题。

So you have to stay alert, which should not be a problem if you are treating warnings as errors.

这篇关于C ++类前向声明​​的缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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