user2321611
user2321611

Reputation: 1079

c++ how to delete a class via pointer to the class

Somewhere in my code I call: A* p = new A; and I put the pointer p in a vector.

Now I want to delete the pointer and the class the pointer is pointing to. like this:

A* p = getpointerfromvector(index); // gets the correct pointer

Delete the pointer from the vector:

vector.erase(vector.begin()+index)

Now I want to delete the class the pointer is pointing to and delete it.

delete p; // (doest work: memorydump)  

or p->~A with ~A the destructor of class A with body: delete this;. (my program quits whenever I call the function.)

Upvotes: 0

Views: 80

Answers (1)

enhzflep
enhzflep

Reputation: 13089

This works for me. Cant compare it to your code since its not all in your post.

#include <stdio.h>
#include <vector>

using std::vector;

class A
{
public:
    A() {mNum=0; printf("A::A()\n");}
    A(int num) {mNum = num; printf("A::A()\n");}
    ~A() {printf("A::~A() - mNum = %d\n", mNum);}
private:
    int mNum;
};

int main ()
{
    A *p;
    vector <A*> aVec;
    int i, n=10;
    for (i=0; i<n; i++)
    {
        p = new A(i);
        aVec.push_back(p);
    }
    int index = 4;
    p = aVec[index];
    aVec.erase(aVec.begin()+index);
    delete(p);
}

Output:

A::A()
A::A()
A::A()
A::A()
A::A()
A::A()
A::A()
A::A()
A::A()
A::A()
A::~A() - mNum = 4

Upvotes: 2

Related Questions