c++ - 保存指向在本地创建的堆的指针
问题描述
我创建了一个“Planet”类,并试图在我的项目的客户端文件中基于该类初始化一个矢量数组。
bool addPlanet(std::vector<Planet>& planets, std::string filePath)
{
std::ifstream infile(filePath, std::ios_base::in);
if (infile.fail()) {
// File could not be opened
return false;
}
std::string planetName, imagePath;
float posX, posY, rotationZ, scaleX, scaleY;
unsigned long long int planetMass;
while (infile >> planetName >> posX >> posY >> rotationZ >> scaleX >> scaleY >> planetMass >> imagePath)
{
Planet* newPlanet = new Planet(sf::Vector2f(posX, posY), rotationZ, sf::Vector2f(scaleX, scaleY), planetMass, imagePath);
planets.push_back(*newPlanet);
}
infile.close();
return true;
}
但我无法弄清楚以下代码是否导致内存泄漏:
while (infile >> planetName >> posX >> posY >> rotationZ >> scaleX >> scaleY >> planetMass >> imagePath)
{
Planet* newPlanet = new Planet(sf::Vector2f(posX, posY), rotationZ, sf::Vector2f(scaleX, scaleY), planetMass, imagePath);
planets.push_back(*newPlanet);
}
我这样想:
我为“Planet”类的新实例分配动态内存。使用 push_back 方法——vector 的内部迭代器成为指向新实例的第二个指针。而当我们退出循环时,vector 中还有一个指向新分配堆的指针。
我是否正确理解了所有内容,或者我只是不擅长阅读文档?
解决方案
您的代码创建一个Planet
对象:
Planet* newPlanet = new Planet(sf::Vector2f(posX, posY), rotationZ, sf::Vector2f(scaleX, scaleY), planetMass, imagePath);
然后,它将这个对象复制到向量中:
planets.push_back(*newPlanet);
但它不会释放原始对象对应的内存。向量只拥有副本,而不是原始Planet
对象。
您可以简单地解决此问题,但根本不使用new
:
Planet newPlanet(sf::Vector2f(posX, posY), rotationZ, sf::Vector2f(scaleX, scaleY), planetMass, imagePath);
planets.push_back(std::move(newPlanet));
在这里,拥有该newPlanet
对象的是代码块。
但是,您可能希望直接使用std::vector::emplace_back()
而不是new
and push_back()
:
planets.emplace_back(sf::Vector2f(posX, posY), rotationZ, sf::Vector2f(scaleX, scaleY), planetMass, imagePath);
这样,向量就获得了Planet
所创建的单个对象的所有权。
推荐阅读
- linux - 如何在 shell 脚本中将 function_1 的输出转换为 function_2?
- python - 我的搜索查询不起作用并显示以下错误,:TypeError: not all arguments convert during string formatting
- javascript - 如何清除按钮单击
- wordpress - 根据在 WooCommerce 中选择的产品类别查询以获取属性?
- python - 如何找到大于平均值/中位数的平均工资
- python - 我们如何用 SQL 比较 python 中的两个对象和数据的内容?
- python - 400 Bad Request:浏览器(或代理)发送了一个服务器无法理解的请求
- java - 具有相同数据类型代码的相同逻辑代码在 Java 中传递,但在 C++ 中不传递?
- regex - 使用负前瞻的正则表达式缺少 group2 的第一个字符
- java - 使用 ArrayList 显示另一个类的值