假设我有一类重新分配
class Foo
{
public:
~Foo() { delete &_bar; }
void SetBar(const Bar& bar)
{
_bar = bar;
}
const Bar& GetBar() { return _bar; }
private:
Bar& _bar;
}
而且我的这个类的用法如下(假设酒吧有一个工作拷贝构造函数)
Foo f;
f.SetBar(*(new Bar));
const Bar* bar = &(f.GetBar());
f.SetBar(*(new Bar(bar)));
delete bar;
我有类似情况这(在代码中我没有写),当我在“删除栏”上设置的断点进行调试时,行,我看到
&f._bar == bar
我的问题是:为什么& f._bar和酒吧指向相同的内存块,如果我离开了“删除吧;”会带来什么后果,从内存管理的角度来看?
非常感谢!
正如所写,代码不能编译。 Foo没有默认的构造函数。 – 2010-01-21 16:36:58
你应该击中那些在头部非常难以编写代码的人 - 引用不打算替代指针。 – 2010-01-21 16:38:45