动态分配对象生成器
Dynamically allocated object producer
看这个班:
//HPP
class A {
public:
A();
~A();
B *fetchNew();
private:
B *currentValue;
}
//CPP
A::A() {}
A::~A {
delete currentValue;
}
B *A::fetchNew() {
delete currentValue;
currentValue = new B();
//apply magic to currentValue
return currentValue;
}
这个类持有一个指向类b实例的指针。每次调用fetchNew()
时,旧的被删除,一个新的被分配,并对它应用魔法,在新的和闪亮的currentValue
返回之后。
这个方法被频繁调用(在现实生活中,它是一个在游戏主循环中返回视图矩阵的方法,所以它每帧被调用一次,大约每秒60次)。
一旦A对象被删除,它将删除当前的currentValue
,否则会泄漏。
有更漂亮的方法来实现这一点吗?
编辑:下面是实际代码,因为它有一个转折(只是
fetchNow()
方法):
glm::mat4x4 *Camera::getViewMatrix() {
//transformation <<-apply shiny and fancy magic;
delete viewMatrix;
viewMatrix = new glm::mat4x4();
*viewMatrix *= glm::mat4_cast(transformation->getRotation());
*viewMatrix = glm::translate(*viewMatrix, transformation->getPosition());
return viewMatrix;
}
有更漂亮的方法来实现这一点吗?
我建议使用 std::unique_ptr<B>
而不是原始指针B*
:
//HPP
#include <memory>
class A {
public:
A();
~A();
std::unique_pty<B> fetchNew();
private:
// You don't need that: B *currentValue;
}
//CPP
A::A() {}
A::~A {
// You don't need that: delete currentValue;
}
std::unique_ptr<B> A::fetchNew() {
// You don't need that: delete currentValue;
std::unique_ptr<B> newValue = std::make_unique<B>();
// apply magic to newValue and dereference using * or -> as with any raw pointer
return newValue;
}
这种方法有几个优点:
- 您不必关心
A
中的删除或内存泄漏 -
fetchNew()
结果的所有权转移在语义上是清晰的 - 这是一个更清晰的API,客户端将知道他们获得了指针的所有权,而不必考虑是否需要删除该实例
- 您为客户端提供了自行确定
B
实例的生命周期范围的灵活性。
对于您编辑的添加,它应该看起来像:
std::unique_ptr<glm::mat4x4> Camera::getViewMatrix() {
//transformation <<-apply shiny and fancy magic;
std::unique_ptr<glm::mat4x4> viewMatrix = std::make_unique<glm::mat4x4>();
*viewMatrix *= glm::mat4_cast(transformation->getRotation());
*viewMatrix = glm::translate(*viewMatrix, transformation->getPosition());
return viewMatrix;
}
相关文章:
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 销毁C++中动态分配的内存(数组对象)
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 动态分配的对象未初始化
- std::p air 会破坏其动态分配的对象吗?
- 动态分配对象中的字段-动态分配更好还是静态分配更好?C++
- 如果您为类的一个对象动态分配内存作为参数,会发生什么
- 使用私有析构函数删除动态分配的对象
- 动态分配许多 Boost::直方图对象
- 如何使用每个对象的单个构造函数参数动态分配C++对象数组?
- 将动态分配对象传递到 boost::any 构造函数中
- 将动态分配的对象添加到对象指针数组中
- 如何删除列表中的动态分配类对象<T>?
- 处理另一个类中类动态分配的对象数组
- 如何使用一些参数初始化动态分配的数组中的对象
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 如何复制或返回包含动态分配的内存的对象
- C 删除指向动态分配对象的指针