C++ 如何通过指向类的指针删除类
c++ how to delete a class via pointer to the class
在我的代码中的某个地方,我调用: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
相关文章:
- 无法删除指针,已触发断点
- 删除指针数组 (C++) 中的元素
- 如果我删除指针,我的C++程序会意外删除系统文件吗?
- 为什么const_cast删除指针的恒常性,而不删除指向常量的指针的恒常性?
- 删除指针后内存泄漏
- 这是系统资源吗?(或者我怎么知道我是否需要删除指针) - 在 C++ 中使用 C
- C++ 从 2 组指针中删除指针
- 当删除 [] 指针工作时,为什么无法获得指向的数组大小?
- 在这种情况下,删除指针数组期间会发生什么?
- 在C++中删除指针数组时析构函数崩溃
- 何时/如何在使用指针后正确删除指针?
- 在C++库中,谁应该删除指针、用户或库?
- 删除指针后阻止对象使用 "this"
- 删除指针后C++尝试/捕获
- 删除指针内存分配以避免内存泄漏
- 删除指针时,未分配被释放的 C++ 指针错误
- 如何从抽象类中删除指针
- 我应该在 v8::外部手动删除指针吗?
- 删除指针
- C 如何删除指针的默认对象成员