c++ - 如何在 C++ 中将对象存储在另一个对象中?

标签 c++

我想确保我正确地创建/销毁了这个对象...

这是我的 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/

相关文章:

c++ - 任意文件类型中的语法突出显示

c++ - 如何以向后方式遍历python和c++中的文件?并且还以向后(从下到上)的方式存储数据?

c++ - 检测到子进程因操作系统内存不足而被终止

c# - 从 C++ 应用程序 (Android NDK) 免费运行 C# 代码

c++ - 修复 Valgrind 错误内存泄漏的错误

c++ - 将 QVariant 转换为 QVector<int>

c++ - 使用 GDI 和 Direct3D 的恼人文本换行

使用 std::atomic 的 C++ 线程安全增量,带模而不带互斥锁

c++ - "72"对 "gcc72-c++"意味着什么

c++ - QComboBox 中的项目需要多少像素?