0

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.)

7
  • 2
    A small clarification on nomenclature: In your case A is the name of a class, while p is a pointer to an object. When you do new A you are creating a new object, not a new class. It is important to keep the notions of class and object separate :) Commented Nov 13, 2013 at 16:58
  • Please show a complete, compilable example that demonstrates the problem. Commented Nov 13, 2013 at 17:00
  • 1
    delete p is correct. If it doesn't work, post an sscce demonstrating the problem. Commented Nov 13, 2013 at 17:00
  • I bet you have wrong index. Commented Nov 13, 2013 at 17:02
  • if I call delete p: i get a memorydump and my program quits Commented Nov 13, 2013 at 17:05

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

I forgot to change my destructor to ~A{} instead of ~A{delete this}
Easily done. It's for just these kinds of oversights, that you should always aim to post an SSCCE - Short Self Contained Correct (Compilable) Example. (sscce.org)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.