未能返回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;
};
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; }
相关文章:
- 为什么 std::unique 不调用 std::sort?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 生成"unique"矩阵
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 我对 std::unique(算法)C++有问题
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++中的指针否定 (!ptr == NULL)
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误