首页 > 解决方案 > 保存指向在本地创建的堆的指针

问题描述

我创建了一个“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 中还有一个指向新分配堆的指针。

我是否正确理解了所有内容,或者我只是不擅长阅读文档?

标签: c++sfmldynamic-memory-allocation

解决方案


您的代码创建一个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()而不是newand push_back()

planets.emplace_back(sf::Vector2f(posX, posY), rotationZ, sf::Vector2f(scaleX, scaleY), planetMass, imagePath);

这样,向量就获得了Planet所创建的单个对象的所有权。


推荐阅读