2010-06-20 93 views
9

下面的代码:C++必须删除一个引用?

class x 
{ 
private: 
someRef& m_ref; 

public: 
x(someRef& someRef):m_ref(someRef) 
{ 
} 

做我需要做的:

~x() 
{ 
    delete m_ref; 
} 

其通过没有得到指针的方式不起作用......

基本上我问: 我是否需要在引用成员上调用析构函数?

+0

这段代码甚至不会编译 – 2010-06-20 11:57:33

+0

如有疑问,看看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

回答

3

不可以。您只能删除指针而不是引用,即使如此,您也只能删除使用new运算符分配的对象。然后你必须确保只删除它们一次。下面是你需要在你的析构函数中使用delete的情况:

class x 
{ 
private: 
someObj* m_ptr; 

public: 
x():m_ptr(new someObj()) 
{ 
} 

~x() 
{ 
    delete m_ptr; 
} 

但一般最好避免连这和使用智能指针来代替。

+0

只是为了澄清,如果父类的析构函数被调用,它是否也会调用通过引用传递的成员的析构函数?我认为这不会因为它没有被班级初始化,但我可能是错的。 – Mel 2013-09-11 15:55:46

+0

这与引用变量有什么关系? – 2013-12-03 15:37:27

16

您只有拥有它需要delete对象号。如果你通过参考,这意味着别人拥有它,因此它是没有必要的,幸好语言阻止了它。

+2

语言如何防止它? – Troubadour 2010-06-20 11:22:01

+0

@Troubadour'foo & a;删除a;'会失败(除非foo是指针类型)。 – tstenner 2010-06-20 11:43:10

+0

@Troubadour:正如OP所说,它根本不会编译。 – 2010-06-20 13:18:53

6

我不认为一个实际上严格来说甚至会删除甚至指针。你删除的是动态分配的对象(或对象数组),指针是一个句柄。如果对象来自新的,并且这个类的责任是在此对象之后清理,那么请致电删除

这在技术上是可能的参考可能指的是动态分配的对象:

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; 
} 

然而,这将是非常糟糕的风格。按照惯例,动态分配对象的“拥有”句柄不应该是一个引用。

2

我想澄清一些误解,你似乎有超出你的问题的意图:

当一个类的析构函数被调用它的所有成员的析构函数被调用为好。

调用delete与调用析构函数不同。 delete显式调用析构函数,并在对象位置调用operator delete,这是一个2部分事情。

+0

只是为了澄清,你提到'它的所有成员'析构函数也被称为'。这是否包含在构造函数中通过引用传递的成员?我会假设它不会因为这些对象不属于类,并且可能拥有构造函数的调用者。 – Mel 2013-09-11 15:58:35

+0

@Mel在这里可能有一些标准引用适用于引用被视为基元并且没有析构函数。无论如何,你的假设是正确的。 – David 2013-09-11 19:47:24

1

对于额外的澄清一个小一点,我想提供以下几点:

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. 
+0

“堆上int的地址”>。< – 2011-08-13 19:15:50

+0

实际上,严格地说,你永远不会“删除一个指针”。您通过将指针传递给delete来删除动态分配的对象。 – 2011-08-13 19:16:26