需要在析构函数中删除指针的情况

问题描述 投票:0回答:1

在我的教科书中,我注意到它删除了析构函数中的指针,我觉得这很奇怪。然后它解释说,免费商店上的address本身被删除,但定位的值却没有。我的问题是,除了自由存储中的指针之外,还有其他情况可以删除析构函数中的指针吗?为了安全起见,我是否应该删除所有指向免费商店的指针?

这是我的意思的注释代码:

class ExampleClass
{
public:
    ExampleClass(); 
    ~ExampleClass() { delete pNum; };

    int exampleMethod() {
        pNum = new int(5);
        return *pNum;
    } /*
      when I call exampleMethod in main(), 
      it assigns a pointer to an address on the free store and the value
      of the address holds 5. When the destructor is called, the pointer is called but the value is
      stranded on the free store and will cause a memory leak. 

      My question is, is it a general rule that we only need to delete pointers 
      in the destructor that to the free store or are there other cases where we need to delete pointers in the destructor?
      */ 

private:
    int* pNum;
};

任何解释将不胜感激。

c++ oop constructor
1个回答
0
投票

你删除的不是指针,而是它指向的内容。

delete pNum;
不会删除
pNum
,而是删除
pNum
指向的整数。当
pNum
不指向通过
int
分配的
new
时,则
delete pNum;
是错误的,它是未定义的。您可能会遇到崩溃或其他问题。

您的调用很好地说明了为什么手动管理资源容易出错。如果您确实管理资源,则需要遵循 3/5 规则。通常,管理资源对于一个类来说就足够了,所以它除了管理资源之外不应该做任何事情。这样的课程比较无聊。他们在构造函数中获取资源并在析构函数中释放它并实现 5 规则,但通常不会做太多其他事情。

std::unique_ptr
就是这样一个班级。

如果您使用

std::unique_ptr
,或其他智能指针或容器,或您自己的自定义5类规则,那么使用它们的类既不需要新建,也不需要手动删除某些内容。你可以遵循0的规则:

class ExampleClass
{
public:

    int exampleMethod() {
        pNum = std::make_unique<int>(42);
        return *pNum;
    }
private:
    std::unique_ptr<int> pNum;
};

但是,如果您确实通过

new
分配了某些内容,那么您必须通过
delete
删除它,否则会出现内存泄漏。

© www.soinside.com 2019 - 2024. All rights reserved.