c++ - 当一个方法只接受 Foo *const 时,我应该 const_cast "this"吗?

标签 c++ qt

我有一个类Foo这是一个 self 引用的树状结构(最低限度):

class Foo {
    public:
        // Gets this child's position relative to it's parent.
        int getPosition() const {
             return parent->indexOf(this);
        }

        int indexOf(const Foo *const child) const {
            return children.indexOf(child); // this line causes an error.
        }
    private:
        Foo *parent;
        QList<Foo *> children;
}

return children.indexOf(child)期待 const T &value根据 QList docs 通过, 这解析为 Foo *const &value对于我的场景。

为了我的getPosition()调用我自己的方法 indexOf()方法需要签名 const Foo *child至少为了通过 this来自 const 方法。 (因为这是 const Foo *const )。

我的代码不会编译为 const Foo *const child无法转换为 Foo *const child对于 QList::indexOf .我的两种方法都没有修改对象状态,因此它们应该是 const(即我不想取消成本 getPosition 来接收非常量 this)。

所以问题是,我如何从 this 开始?在 const 上下文中 ( const Foo *const ) 到什么 QList::indexOf需要。我应该 const 类型转换 this里面getPosition因为我知道我的 indexOf (以及随后的调用)不会改变它?

还有什么我应该做的吗?也许我的设计有问题。

最佳答案

我认为这是 const_cast 的一个完全合理的用例,但是它不是 this 您需要 const_cast,而是 child 。在这种情况下,QList::indexOf 需要一个指向 Foo (Foo* const) 的常量指针,但是 child是指向常量 Foo (const Foo* const) 的常量指针。没有从 Foo* constconst Foo* const 的隐式转换,因为这会从指向的值中删除常量。

因此,为了修复您的代码,我会将行更改为

return children.indexOf(const_cast<Foo*>(child));

你知道 QList::indexOf 不会修改 child 指向的任何内容,因此这不会产生未定义的行为。然而,我会添加一条评论来解释为什么 const_cast 是必要的。

关于c++ - 当一个方法只接受 Foo *const 时,我应该 const_cast "this"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17156558/

相关文章:

C++ 使用继承为对象分配空间

c++ - 非指针成员变量的虚析构函数

QT/QT 设计师问题 : auto-resizing widget

qt - 在槽函数运行时显示一个 "Please wait..."框

c++ - 如何让 Qt Websocket 和 QNetworkRequest (HTTP) 使用同一个连接?

c++ - 如何设计相互依赖的策略类实现

c++ - 为什么我们使用 'this->' 而不是 'this.' 来访问成员?

c++ - 从键值对进行双向查找

qt - 如何让QT文本每隔几毫秒出现一次(闪烁)

python - PyQt 中信号处理程序会内存泄漏吗?