看看这个类:
//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()
被调用时,旧的被删除,一个新的被分配并应用魔法,在新的之后并返回 Shiny 的 currentValue
。
这个方法被调用的非常频繁(现实生活中,它是在游戏主循环中返回一个 View 矩阵的方法,所以每帧调用一次,大约一秒钟调用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;
}
最佳答案
Is there a prettier way to achieve this?
我更推荐使用 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;
}
关于c++ - 动态分配的对象生产者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40442668/