Search code examples
c++qtconst-cast

Qt example const_cast


I was checking one of Qt's examples. In the example they have a simple TreeItem class to be placed on in a tree:

class TreeItem
{
public:
    explicit TreeItem(const QVector<QVariant> &data, TreeItem *parentItem = nullptr);
    ~TreeItem();

    void appendChild(TreeItem *child);

    TreeItem *child(int row);
    int childCount() const;
    int columnCount() const;
    QVariant data(int column) const;
    int row() const;
    TreeItem *parentItem();

private:
    QVector<TreeItem*> m_childItems;
    QVector<QVariant> m_itemData;
    TreeItem *m_parentItem;
};

In the implementation of the int row() const; method, they use a const_cast:

int TreeItem::row() const
{
    if (m_parentItem)
        return m_parentItem->m_childItems.indexOf(const_cast<TreeItem*>(this));

    return 0;
}

To me, this smells like undefined behavior. What if this object is actually defined as const? But since this is in the official website as an example I want to know if I am right or not. At fist I thought maybe the intention is to never create a const TreeItem but then it would be pointless to mark the row method as const.
Question: Is it fine to use const_cast on this all the time as in the example?


Solution

  • This is not undefined behavior. const_cast is only undefined behavior if the object you start with is const and you modify the the object you get from the cast.

    return m_parentItem->m_childItems.indexOf(const_cast<TreeItem*>(this));
    

    Is not going to modify const_cast<TreeItem*>(this) since indexOf takes a const T&.