未能返回unique_ptr

Failing to return a unique_ptr

本文关键字:ptr unique 返回      更新时间:2023-10-16

HPP:

class Camera {
public:
    Camera(float FOV, float nearPlane, float farPlane);
    std::unique_ptr<glm::mat4x4> getProjectionMatrix();
private:
    std::unique_ptr<glm::mat4x4> projectionMatrix;
};

CPP:

Camera::Camera(float FOV, float nearPlane, float farPlane) {
    float aspectRatio = DisplayManager::displayWidth / DisplayManager::displayHeight;
    projectionMatrix = std::make_unique<glm::mat4x4>();
    *projectionMatrix = glm::perspective(FOV, aspectRatio, nearPlane, farPlane);
}
std::unique_ptr<glm::mat4x4> Camera::getProjectionMatrix() {
    //std::unique_ptr<glm::mat4x4> projectionMatrix = std::make_unique<glm::mat4x4>();
    //*projectionMatrix = glm::perspective(90.0f, 1.333f, 0.1f, 1000.0f);
    return std::move(projectionMatrix);
}

看看这两行评论。无论它们是否被注释掉,程序都会编译,但如果被注释掉了,数据就会被破坏。

如何编写一个getter来返回该类的私有成员unique_ptr?如何在构造函数中正确设置unique_ptr?

这里有一个更好的主意:停止不必要的内存分配。让Camera直接存储glm::mat4x4,而不是作为unique_ptr。C++不是Java;您不必使用new分配所有内容。所有的代码都变得简单多了:

Camera::Camera(float FOV, float nearPlane, float farPlane)
    : projectionMatrix(glm::perspective(FOV, (DisplayManager::displayWidth / DisplayManager::displayHeight), nearPlane, farPlane))
{
}
glm::mat4x4 &Camera::getProjectionMatrix() { return projectionMatrix; }

但是,如果您必须在Camera中使用unique_ptr,那么您应该返回一个引用,而不是智能指针:

glm::mat4x4 &Camera::getProjectionMatrix() { return *projectionMatrix; }