Self-deleting pointer class

closed account (10oTURfi)
I'm trying to create suicidal pointer. This doesn't have any particular purpose, because it deletes pointer as soon as first pointer is out of scope, but I thought it would be fun.

This is code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
template<class T>
struct Pointer
{
    T* _Ptr;
    Pointer() { _Ptr = NULL; }
    Pointer(T* _Ptr) : _Ptr(_Ptr) {}
    ~Pointer() { if(_Ptr != NULL) { delete _Ptr; _Ptr = NULL; } }
    T& operator*() { return *_Ptr; }
    void operator=(T* _Ptr){ delete this->_Ptr; this->_Ptr = _Ptr; }
    void operator=(const Pointer& Pointer) { this->_Ptr = Pointer._Ptr; }
};

typedef Pointer<int> intptr;

int main()
{
    while(true) // Try to leak memmory
    {
        intptr p(new int);
        intptr d = new int;
        d = new int;
        d = new int;
        *p = 5;
        *d = 10;
        intptr c;
        c = d;
        cout << *p << " " << *d << " " << *c << " ";
    }
}


Now the thing is, it crashes, and I do not know why.
Where's the problem?
Deleting the same pointer more than once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <cstdlib>
#include <iostream>

using namespace std;


template<class T>
struct Pointer
{
    T* _Ptr;
    Pointer() { _Ptr = NULL; }
    Pointer(T* _Ptr) : _Ptr(_Ptr) {}
  ~Pointer() { if(_Ptr != NULL) { cout<< "deleting " << _Ptr << endl; delete _Ptr; _Ptr = NULL; } }
    T& operator*() { return *_Ptr; }
  void operator=(T* _Ptr){ cout<< "deleting " << this->_Ptr << endl; delete this->_Ptr; this->_Ptr = _Ptr; }
    void operator=(const Pointer& Pointer) { this->_Ptr = Pointer._Ptr; }
};

typedef Pointer<int> intptr;

int main()
{
    while(true) // Try to leak memmory
    {
        intptr p(new int);
        intptr d = new int;
        d = new int;
        d = new int;
        *p = 5;
        *d = 10;
        intptr c;
        c = d;
        cout << *p << " " << *d << " " << *c << " ";
    }   
}
I did not test the code but it seems the problem is connected with creating a temporary object in the statement

intptr d = new int;

Without optimization the compiler at first creates a temporary object using constructor

Pointer(T* _Ptr) : _Ptr(_Ptr) {}

Then the compiler uses implicitly defined copy constructor to copy the temporary object to d. And then it deletes the temporary object. So d contains invalid pointer.
Last edited on
closed account (10oTURfi)
@Moschops
I see... Is there a way to prevent that?
I think you should make a copy of object the pointter passed as argument of constructor/copy constructor and the copy assignment operator refers to.
closed account (10oTURfi)
@vlad
Yes that might fix the problem, however, I wanted both pointers to point to same object.
Topic archived. No new replies allowed.