C++ 如何通过指向类的指针删除类

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

本文关键字:删除 指针 何通过 C++      更新时间:2023-10-16

在我的代码中的某个地方,我调用:A* p = new A;,我将指针p放在一个向量中。

现在我想删除指针和指针指向的类。喜欢这个:

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

从矢量中删除指针:

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

现在我想删除指针指向的类并将其删除。

delete p; // (doest work: memorydump)  

p->~A ~A 类 A 的析构函数与主体:delete this; .(每当我调用函数时,我的程序都会退出。

这对

我有用。无法将其与您的代码进行比较,因为它并非全部在您的帖子中。

#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 = %dn", 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);
}

输出:

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