AK_*_*AK_ 10 c++ destructor reference
在以下代码中:
class x
{
private:
someRef& m_ref;
public:
x(someRef& someRef):m_ref(someRef)
{
}
Run Code Online (Sandbox Code Playgroud)
我需要做什么:
~x()
{
delete m_ref;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,没有得到指针...
基本上我在问:我是否需要在参考成员上调用析构函数?
我不认为一个人实际上严格来说甚至会删除指针.您删除的是指针是句柄的动态分配对象(或对象数组).如果对象来自对new的调用,并且此类负责清除此对象后,则调用delete.
从技术上讲,引用可能是指动态分配的对象:
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;
}
Run Code Online (Sandbox Code Playgroud)
然而,这将是非常糟糕的风格.按照惯例,动态分配的对象的"拥有"句柄不应该是引用.
不可以。您只能删除指针,不能删除引用,即便如此,您也只能删除使用new运算符分配的对象。然后你必须确保只删除它们一次。以下是您需要delete在析构函数中使用的情况:
class x
{
private:
someObj* m_ptr;
public:
x():m_ptr(new someObj())
{
}
~x()
{
delete m_ptr;
}
Run Code Online (Sandbox Code Playgroud)
但总的来说,最好避免这种情况,而是使用智能指针。