向量推回调用析构函数时调用析构函数

vector pushback calling destructor on calling a function

本文关键字:调用 析构函数 回调 向量      更新时间:2023-10-16

我有一个结构

struct Point
{
int x,y;
Point(int _x,int _y)
{
x=_x,y=_y;
}
int GetX()
{
return x;
}
int GetY()
{
return y;
}
}

在我的程序中,如果我调用

Point *ptr=new Point(5,10);
vector<Point>allpts;
allpts.push_back(Point(ptr->GetX(),ptr->GetY());

在此行之后

PTR 在推回后被删除,而不应该

。为什么会这样?

在示例中,使用仅使用参数副本初始化所有数据成员的构造函数是没有意义的。此外,当数据成员公开时,getter 也没有价值。提出索赔的唯一兴趣

PTR 在推回后被删除,而不应该

可观察,即告知正在销毁的对象的决定函数,在您的示例中缺失。具有相同效果的代码:

#include <vector>
#include <iostream>
struct Point
{
int x, y;
~Point() { std::cout << "Point dtor called for " << this << 'n'; }
};
int main()
{
Point *ptr = new Point{ 5, 10 };
std::cout << "ptr points to " << ptr << 'n';
std::vector<Point>allpts;
allpts.push_back(*ptr);
// delete ptr;
}

样本输出(不含delete ptr;(:

ptr points to 0018DE58
Point dtor called for 0018DBF0

示例输出(带delete ptr;(:

ptr points to 0018DE58
Point dtor called for 0018DBF0
Point dtor called for 0018DE58

如您所见,除非显式完成,否则ptr指向的对象不会被删除。