问题描述
我有这样的类:
class Inner;
class Cont
{
public:
Cont();
virtual ~Cont();
private:
Inner* m_inner;
};
,构造函数创建 Inner
与 new
和析构函数 delete
现在我想更改此代码以使用 auto_ptr
,所以我写:
in the .cpp, the constructor creates an instance of Inner
with new
and the destructor delete
s it. This is working pretty well.
Now I want to change this code to use auto_ptr
so I write:
class Inner;
class Cont
{
public:
Cont();
virtual ~Cont();
private:
std::auto_ptr<Inner> m_inner;
};
现在,构造函数初始化了 auto_ptr
析构函数什么也不做。
Now, the constructor initialized the auto_ptr
and the destructor does nothing.
但它不工作。当我实例化这个类时,问题似乎出现。我收到此警告:
But it doesn't work. the problem seem to arise when I'm instantiating this class. I get this warning:
好吧,这显然很不好,我明白为什么会发生,编译器不知道当实例化 auto_ptr< Inner>
Well, this is obviously very bad and I understand why it happens, The compiler doesn't know about the d'tor of Inner
when instantiating the template of auto_ptr<Inner>
所以我的问题:是否有一种方法使用 auto_ptr
与前向声明,就像我在使用纯平指针的版本中一样?
每个类我声明一个指针是一个巨大的麻烦,有时,只是不可能的 #include
So my question: Is there a way to use auto_ptr
with a forward declaration like I did in the version that uses just plain pointers?
Having to #include
every class I declare a pointer to is a huge hassle and at times, just impossible. How is this problem usually handled?
推荐答案
您需要包含定义 class Inner
到 Cont ::〜Cont()
实现所在的文件。这种方式你仍然有一个向前的声明,在teh头定义 class Cont
,编译器看到 class Inner
定义,析构函数。
You need to include the header defining class Inner
into the file where Cont::~Cont()
implementation is located. This way you still have a forward declaration in teh header defining class Cont
and the compiler sees class Inner
definition and can call the destructor.
//Cont.h
class Inner; // is defined in Inner.h
class Cont
{
virtual ~Cont();
std::auto_ptr<Inner> m_inner;
};
// Cont.cpp
#include <Cont.h>
#include <Inner.h>
Cont::~Cont()
{
}
这篇关于C ++:auto_ptr +向前声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!