使用智能指针释放在堆上分配的内存(超出作用域就释放)
class Entity {
private:
float x, y;
public:
Entity(float x,float y):x(x),y(y) {
std::cout<<"Created Entity!"<<std::endl;
}
~Entity() {
std::cout << "Destroyed Entity!" << std::endl;
}
};
//智能指针,可以将堆上分配的指针内存释放掉
//以下类是在栈上分配内存
class ScopedPtr {
private:
Entity* ptr;
public:
ScopedPtr(Entity* e):ptr(e){
}
~ScopedPtr() {
delete ptr;
}
};
int main() {
{
ScopedPtr s = new Entity(1, 2);
}
}
标签:float,Entity,智能,栈堆,分配,指针 From: https://www.cnblogs.com/wangkaixin-yy/p/17657385.html