惰性求值和 const 正确性问题
我制作了一个 openGL 相机类,它使用惰性求值通过 getter 函数提供最终的投影或模型-视图-投影矩阵。用户在实例的整个生命周期中提供各种相机参数(FOV、位置等),但不是每次更改参数时都重新计算投影矩阵和/或 MVP 矩阵,而是设置“已更改”标志(即旧的缓存矩阵现在无效)。每当用户请求更新的最终矩阵时,都会重新计算该矩阵,缓存结果并返回常量引用。
一切听起来都很好,直到我
const QMatrix4x4& oE_GLCamera::getModelViewProjection() const;
从 const oE_GLCamera 实例调用 my: 函数...我在应用程序中的各处使用 const 引用从 CAD 视口提取相机数据而不更改相机,但我的 getter 函数对成员变量执行惰性评估(如果它们是)无效 - 因此破坏了常量正确性。
是否有我不知道的语言功能或设计范例可以帮助解决这个问题?或者惰性求值从根本上与常量正确性不兼容?我知道 const_cast<>,我自己从未使用过它,但读过一些关于它的内容,归结为:如果你使用它,那么你已经在某个地方出错了。或者它会成为我的救世主吗?
任何建议都会受到极大的欢迎, 凸轮
I have made an openGL camera class that uses lazy evaluation to provide the final projection or model-view-projection matrices through getter functions. The user provides the various camera parameters throughout the life of the instance (FOV, position, etc. ), but rather than have the projection matrix and/or MVP matrix recalculated every time a parameter is changed, a 'changed' flag is set (i.e. the old cached matrix is now invalid). Whenever the user then requests the updated final matrix, it is recalculated, the result cached, and a const reference returned.
Everything sounds fine until I call my:
const QMatrix4x4& oE_GLCamera::getModelViewProjection() const;
function from a const oE_GLCamera instance... I use const references everywhere in my app to extract camera data from CAD viewports without changing the camera, but my getter function performs lazy evaluation on member variables if they are invalid - therefore breaking const-correctness.
Is there a language feature or design paradigm I'm unaware of to help with this? Or is lazy evaluation fundamentally incompatible with const-correctness? I am aware of const_cast<>, I have never used it myself but have a read few things about it which boil down to: If you have you use it, you have already gone wrong somewhere. Or will it be my saviour?
Any advice will be greatfully received,
Cam
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许,
可变
?标记为
mutable
的类成员始终是非const
,即使它是通过指向所属类的引用或指针访问的,该类是const
引用或指向const
的指针。Perhaps,
mutable
?A member of a class that is marked as
mutable
is always non-const
even if it is accessed via a reference or pointer to the owning class which is aconst
reference or a pointer toconst
.