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是否被破坏并释放内存,还是会继续占用堆内存?
当您在堆栈上声明变量时,它们的析构函数将在超出范围时被调用
{
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)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |