问题描述
我有这门课:
class aa
{
public:
int i = 0;
~aa(){
std::cout << "killin in the name of" << std::endl;
}
};
我想制作这个类的向量。首先我想 o 保留所需的大小:
int main()
{
std::vector<aa> vec;
vec.reserve(2);
vec[0] = *(new aa());
vec[1] = *(new aa());
//use the vector
vec.clear();
return 0;
}
但是没有调用析构函数。
另一方面,当我使用 push_back
int main()
{
std::vector<aa> vec;
vec.push_back(*(new aa()));
vec.push_back(*(new aa()));
//use the vector
vec.clear();
return 0;
}
为什么?
解决方法
std::vector
已经为您进行了内存管理。
当您将 std::vector
与这样的简单类一起使用时,您不需要任何 new
或 delete
调用。
保留
在幕后,reserve
只是确保预先分配一块内存以保存指定数量的成员变量。
调整大小
在幕后,resize
实际上会创建 n
新对象。您不需要显式调用 new
。
你的例子
代码 *(new aa())
将在堆上创建一个新的 aa
对象。当您编写 vec[0] = *(new aa());
时,它会尝试将新对象的内容复制到位于地址 vec[0]
中的对象。因此,此时有 2 个不同的对象处于活动状态……一个对象 vec[0]
在内存中的一个位置,另一个对象在内存中的其他位置。
更糟糕的是,您现在调用了 new
并且从未删除该对象。因此,您会出现内存泄漏。
你可能想要的
几乎可以肯定,您会想要其中一种情况。
创建一个向量,然后调整其大小以包含 n
元素。然后使用这些元素:
int main() {
std::vector<aa> vec;
vec.resize(2);
vec[0].i = ...;
vec[1].i = ...;
//use the vector
return 0;
}
push_back
元素,当你想添加东西时
int main() {
std::vector<aa> vec;
vec.push_back(aa()); // Creates a new aa instance and copies into the vector
aa obj;
vec.push_back(obj); // Copies the existing object's data into a new object in the vector.
//use the vector
return 0;
}
vector 的析构函数会适当地删除所有内存。在这个例子中不需要明确清除。
您可以使用更高级的方法来使用 vector,但在您理解此代码之前,您可能应该只坚持这些基础知识。