如果我在c ++中的方法中创建对象,它们会在函数返回时自动销毁,还是会继续占用内存?

ara*_*guy 1 c++

void Player::draw(sf::RenderTarget& target, sf::RenderStates states) const
{

    sf::CircleShape c0;
    c0.setFillColor(sf::Color::Red);
    c0.setPointCount(4);
    c0.setRadius(1);
    c0.setPosition(sf::Vector2f(point[0].x, point[0].y));

    sf::CircleShape c1;
    c1.setFillColor(sf::Color::Red);
    c1.setPointCount(4);
    c1.setRadius(1);
    c1.setPosition(sf::Vector2f(point[1].x, point[1].y));

    target.draw(c0);
    target.draw(c1);
}
Run Code Online (Sandbox Code Playgroud)

我正在学习c ++.正如您所看到的,我在draw方法中创建CircleShape对象,该方法在一秒钟内运行60次.我在网上读到c ++中的对象存储在堆内存中,因此需要手动释放.当draw方法返回时,对象c0和c1是否被破坏并释放内存,还是会继续占用堆内存?

Cor*_*mer 5

当您在堆栈上声明变量时,它们的析构函数将在超出范围时被调用

{
    int a = 5;
}
// a is now out of scope, it's destructor was called
Run Code Online (Sandbox Code Playgroud)

如果从堆中分配,则必须尽量清理内存

{
    int* a = new int(5);
}
// a was just leaked, unless you had a pointer to it later
Run Code Online (Sandbox Code Playgroud)

你必须要清理它

{
    int* a = new int(5);
    delete a;
}
Run Code Online (Sandbox Code Playgroud)

从C++ 11开始,<memory>如果你需要堆分配内存,我会强烈建议使用,但仍然需要RAII清理.

#include <memory>
{
    std::unique_ptr<int> a = std::make_unique<int>(5);
}
// a falls out of scope, the unique_ptr ensures the memory is cleaned up
Run Code Online (Sandbox Code Playgroud)

  • @Puppy他**可以**但他不**必须**.使用`<memory>`允许RAII托管堆内存,这很好,我主张人们走这条路,我试图明确你什么时候做,而不必手动清理内存. (5认同)
  • @Puppy当你的意思是"应该"时,你一直说"必须"."必须"意味着不正确的,非法的或未定义的代码."应该"意味着强烈的偏好. (2认同)