简体   繁体   English

delete 在类中删除指针数据成员的位置

[英]the location of delete in the class to delete pointer data member

I write a simple class, I just wanna know where I should delete my pointer.我写了一个简单的类,我只想知道我应该在哪里删除我的指针。

#include<iostream>


class test
{
private:
    int* sum{new int};


public:
    int addFunc(int num1 = 5, int num2 = 2)
    {
        *sum = num1 + num2;
        return *sum;
    }

    void print()
    {
        std::cout << *sum << std::endl;
    }

};

int main()
{
    test obj;
    obj.addFunc();
    obj.print();
}

I know how to use unique pointers to get rid of deleting pointers, should I delete my pointer after returning it or somewhere else.我知道如何使用唯一指针来摆脱删除指针,我应该在返回指针后还是在其他地方删除指针。

You delete it in the destructor.你在析构函数中删除它。 But if you're managing raw memory you'll also have to implement a suitable copy constructor & copy assignment operator and their move counterparts.但是,如果您正在管理原始内存,您还必须实现一个合适的复制构造函数和复制赋值运算符以及它们的移动对应物。

In 99%+ of these cases you'll just want to use automatic lifetime or smart pointers instead.在 99% 以上的情况下,您只想使用自动生命周期或智能指针。

Short answer: never, meaning at program end.简短回答:从不,意思是在程序结束时。

The problem is that your class is copyable.问题是您的课程是可复制的。 If you delete the pointer in destructor (which would be the correct place for something allocated at construction time), you will get a dangling pointer in the following use case:如果您删除析构函数中的指针(这将是在构造时分配的正确位置),您将在以下用例中得到一个悬空指针:

  • you pass a reference to a test object to a function您将test对象的引用传递给函数
  • inside that function you copy the object to a local object: the pointer will be copied so both the original object and the local copy will point the the same int在该函数中,您将对象复制到本地对象:指针将被复制,因此原始对象和本地副本都将指向相同的 int
  • at the end the the function, the local object will be destroyed.在函数结束时,本地对象将被销毁。 If if deletes the int, the original will get a dangling pointer.如果删除 int,则原始将获得一个悬空指针。

Long story made short: as soon as you use allocation at construction time, you should care for the copy/move construction and assignment, and destruction.长话短说:一旦您在构造时使用分配,您就应该关心复制/移动构造和分配以及销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM