我想确保我正确地创建/销毁了这个对象...
这是我的 Camera 对象的定义,其中包含对 Vector 对象的引用:
#ifndef CAMERA_H
#define CAMERA_H
#include "vector.h"
class Camera {
private:
Vector* location;
Vector* direction;
float velocity;
public:
Camera();
~Camera();
};
#endif
在构造函数中创建:
#include "camera.h"
Camera::Camera() {
location = new Vector(1.0, 1.0, 1.0);
direction = new Vector(1.0, 1.0, 1.0);
velocity = 0.0;
}
Camera::~Camera() {
delete location;
delete direction;
}
然后,每当我想要一个相机对象时,我只需调用 Camera camera
。
当变量
camera
离开时,我的假设是否正确? 范围,将调用析构函数,我不会遭受任何内存 泄漏?如果我想在范围关闭之前删除变量
camera
,是 执行delete camera
是否正确?
最佳答案
Am I correct in assuming that when the variable camera goes out of scope, the destructor will be called and I won't suffer any memory leak?
是的
If I want to remove the variable camera before the scope closes, is it correct to perform delete camera?
不,相机不是由 new
运算符分配的,您不能删除它,只能保留它直到它超出范围。除非调用 new/delete
强制对象持续时间。
潜在的内存泄漏:
在下面的代码中,有可能会泄漏内存。如果构造 location
完成但 direction = new Vector(1.0, 1.0, 1.0);
失败并抛出异常,则不会调用相机析构函数 location
内存泄漏。
Camera::Camera() {
location = new Vector(1.0, 1.0, 1.0);
direction = new Vector(1.0, 1.0, 1.0);
velocity = 0.0;
}
更好的解决方案: 无需为 Vector 成员引入指针。应优先使用自动存储。
class Camera {
private:
Vector location;
Vector direction;
float velocity;
public:
Camera()
: location(1.0, 1.0, 1.0),
direction(1.0, 1.0, 1.0),
velocity(0.0f)
{
}
};
关于c++ - 如何在 C++ 中将对象存储在另一个对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14422453/