0

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.

Amin Khormaei
  • 205
  • 3
  • 7
  • 18

2 Answers2

3

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.

Hatted Rooster
  • 33,170
  • 5
  • 52
  • 104
2

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
  • 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
  • at the end the the function, the local object will be destroyed. If if deletes the int, the original will get a dangling pointer.

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.

Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199