提问人:Zoltán Orosz 提问时间:2/2/2023 最后编辑:wohlstadZoltán Orosz 更新时间:2/2/2023 访问量:145
如果也有 const 吸气器,如何使用 non-const getter?
How to use the non-const getter if there's a const one too?
问:
如果我的类的返回类型既是 const 又是 non-const,我如何使用 non-const 的?
类 (MeshManipulator.h):
namespace vortex::meshSculptEngine
{
class MeshManipulator
{
public:
...
topologyMesh::Mesh* getMesh();
const topologyMesh::Mesh* getMesh() const;
...
};
}
我想使用 Mesh 的代码 (SimpleMeshCorrector.cpp):
void SimpleMeshCorrector::smoothBoundaryLoops(float distance)
{
if (!_boundaryLoops.empty()) {
Mesh* mesh = getEngine()->getManipulator()->getMesh();
...
}
}
我收到以下错误:
不能使用类型为“const vortex::topologyMesh::Mesh*”的值 初始化类型为“vortex::topologyMesh::Mesh*”的实体
我可以使用,但我只是觉得这不是解决这个问题的正确方法。const_cast
答:
2赞
Friedrich
2/2/2023
#1
根本原因是(如注释中所述)返回 .在对象上,只能调用声明的方法。因此,getter 总是被调用,而不是非版本。getManipulator()
const MeshManipulator*
const
const
const
const
根据上下文,有三种方法可以继续:
- 使用(或写入)返回可变 .
MeshManipulator*
- 将 复制到本地可变对象。
const Mesh*
- 用于能够就地更改对象。然而,这违背了恒常的目的。此外,如果声明了指向的对象,这将导致未定义的行为。所以要小心使用。
const_cast<Mesh*>
const
评论
0赞
Passer By
2/2/2023
不,第三个是不可接受的。它邀请UB对你尖叫。
0赞
Friedrich
2/2/2023
@PasserBy 我同意除非你知道自己在做什么,否则不应该这样做(顺便说一句,我的第一个建议也是如此)。你有什么建议?我怎样才能改进这个答案?
0赞
Passer By
2/2/2023
第一个很好,有很多合法的用例,你有什么反对意见? 莫。改变声明的对象是 UB。const_cast
const
0赞
Friedrich
2/2/2023
@PasserBy 我编辑了我的帖子以解决 UB 的危险。如果还有其他问题,请告诉我。我对第一个的反对意见是,声明任何事情必须有理由.因为不方便而扔掉可能会引起副作用。所以在做之前你必须做功课。与 相同。const
const_cast
评论
getEngine()
getManipulator()
const
const_cast
get()
get_mutable()
get() const
get_mutable()