I want to make sure that I’m creating/destroying this object properly…
This is the definition of my Camera object which contains references to Vector objects:
#ifndef CAMERA_H
#define CAMERA_H
#include "vector.h"
class Camera {
private:
Vector* location;
Vector* direction;
float velocity;
public:
Camera();
~Camera();
};
#endif
which are created in the constructor:
#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;
}
then, whenever I want a camera object I simply call Camera camera.
-
Am I correct in assuming that when the variable
cameragoes out of
scope, the destructor will be called and I won’t suffer any memory
leak? -
If I want to remove the variable
camerabefore the scope closes, is
it correct to performdelete camera?
yes
No, camera is not allocated by
newoperator, you can not delete it, just leave it until it goes out of scope. Unless callnew/deleteto force object duration.Potential memory leak:
In below code, there is a chance to leak memory. if constructs
locationfinishes butdirection = new Vector(1.0, 1.0, 1.0);fails and exception is thrown, Camera destructor won’t be called thuslocationmemory is leaked.A better solution:
There is no need to introduce pointer for Vector members. Use automatic storage should be preferred.