我读过C++:auto_ptr + 前向声明?及其答案,尤其是被接受的答案,我知道在结合 auto_ptr 和 forward 声明的类时的陷阱。但是我遇到了这个相同模式的运行时问题,这个问答似乎没有涵盖(以及我检查的所有其他auto_ptr 标记的问题)。
在销毁我Outer
的 -like 类[1]时,我有时会遇到访问冲突,有时我只观察到丢失的析构函数调用。
// Outer.h - an example header
#include <uncopyable.h>
#include <memory>
class Inner;
class Outer: private Uncopyable
{
public:
Outer()
~Outer();
private:
std::auto_ptr<Inner> inner;
};
我在 cpp 文件中实现构造函数和析构函数,并且存在Inner
类型的定义。
// Outer.cpp - an example implementation
#include "Outer.h" //< I use this include order to ensure compileability
#include "Inner.h" //< for units including Outer.h without preconditions
Outer::Outer(): inner(new Inner) {}
Outer::~Outer() {}
如果我:
- 包括
Inner.h
在Outer.h
或 - 显式调用
inner.reset()
我处理仅使用 C++-Builder 6 编译的遗留代码,所以我必须坚持,std::auto_ptr
因为它是编译器似乎支持的唯一 smart_ptr 实现,所以(目前)没有替代这种类型(我知道已弃用)由 C++11)。
我的问题:我在这里做错了什么,或者它可能是 BCB6 [2]中的一个众所周知的错误?
附加说明我预计在阅读 Herb Sutter 的文章Using auto_ptr Effectively后,在不完整类型上使用 auto_ptr 是安全的,包装指针数据成员部分处理它。因此,我上面描述的问题是一个非常令人困惑的经历。
- [1]这个例子被删减来讨论 auto_ptr 使用的正式结构。
- [2] Borland C++ 5.6.4 和 C++-Builder 6 (upd4) 附带的 STL