下面的代码:C++必须删除一个引用?
class x
{
private:
someRef& m_ref;
public:
x(someRef& someRef):m_ref(someRef)
{
}
做我需要做的:
~x()
{
delete m_ref;
}
其通过没有得到指针的方式不起作用......
基本上我问: 我是否需要在引用成员上调用析构函数?
下面的代码:C++必须删除一个引用?
class x
{
private:
someRef& m_ref;
public:
x(someRef& someRef):m_ref(someRef)
{
}
做我需要做的:
~x()
{
delete m_ref;
}
其通过没有得到指针的方式不起作用......
基本上我问: 我是否需要在引用成员上调用析构函数?
不可以。您只能删除指针而不是引用,即使如此,您也只能删除使用new
运算符分配的对象。然后你必须确保只删除它们一次。下面是你需要在你的析构函数中使用delete
的情况:
class x
{
private:
someObj* m_ptr;
public:
x():m_ptr(new someObj())
{
}
~x()
{
delete m_ptr;
}
但一般最好避免连这和使用智能指针来代替。
只是为了澄清,如果父类的析构函数被调用,它是否也会调用通过引用传递的成员的析构函数?我认为这不会因为它没有被班级初始化,但我可能是错的。 – Mel 2013-09-11 15:55:46
这与引用变量有什么关系? – 2013-12-03 15:37:27
您只有拥有它需要delete
对象号。如果你通过参考,这意味着别人拥有它,因此它是没有必要的,幸好语言阻止了它。
语言如何防止它? – Troubadour 2010-06-20 11:22:01
@Troubadour'foo & a;删除a;'会失败(除非foo是指针类型)。 – tstenner 2010-06-20 11:43:10
@Troubadour:正如OP所说,它根本不会编译。 – 2010-06-20 13:18:53
我不认为一个实际上严格来说甚至会删除甚至指针。你删除的是动态分配的对象(或对象数组),指针是一个句柄。如果对象来自新的,并且这个类的责任是在此对象之后清理,那么请致电删除。
这在技术上是可能的参考可能指的是动态分配的对象:
int main()
{
//in principle a reference can also refer to a dynamically allocated object
x var(*new someRef);
}
//and if that is the intended usage:
x::~x()
{
delete &m_ref;
}
然而,这将是非常糟糕的风格。按照惯例,动态分配对象的“拥有”句柄不应该是一个引用。
我想澄清一些误解,你似乎有超出你的问题的意图:
当一个类的析构函数被调用它的所有成员的析构函数被调用为好。
调用delete
与调用析构函数不同。 delete
显式调用析构函数,并在对象位置调用operator delete
,这是一个2部分事情。
对于额外的澄清一个小一点,我想提供以下几点:
int *pi = new int;
//int& ir = pi; // can't do
// this a reference to the pointer but it is an error
// because or the type difference int& vs int* and
// static_cast won't help. reinterpret_cast would allow
// the assignment to take place but not help the 'delete ir'
int& ir = *pi; // this is OK - a reference to what the pointer points to.
// In other words, the the address of the int on the heap.
//delete ir; // can't do, it is a reference and you can't delete non-pointers.
delete &ir; // this works but it is still not "deleting a reference".
// The reference 'ir' is another name for the heap-based int.
// So, &ir is the address of that int, essentially a pointer.
// It is a pointer that is being used by delete, not a reference.
“堆上int的地址”>。< – 2011-08-13 19:15:50
实际上,严格地说,你永远不会“删除一个指针”。您通过将指针传递给delete来删除动态分配的对象。 – 2011-08-13 19:16:26
这段代码甚至不会编译 – 2010-06-20 11:57:33
如有疑问,看看shared_ptr的[1],它会照顾所有你的参考和指针。 [1] http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/shared_ptr.htm – Gianni 2010-06-20 12:14:24