未能 return 一个 unique_ptr

Failing to return a unique_ptr

HPP:

class Camera {
public:
    Camera(float FOV, float nearPlane, float farPlane);

    std::unique_ptr<glm::mat4x4> getProjectionMatrix();

private:
    std::unique_ptr<glm::mat4x4> projectionMatrix;
};

菲律宾共产党:

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 那个 returns 一个 unique_ptr 那个是 class 的私有成员?如何在构造函数中正确设置 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,那么您应该 return 引用,而不是智能指针:

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