Martin Delille
Martin Delille

Reputation: 11780

reference to type 'Item *const' could not bind to an rvalue of type 'const Item *'

I try to suppress a const item pointer from a list of none const item:

#include <QString>
#include <QList>

class Item {
public:
    Item(QString name) : _name(name) {
    }
private:
    QString _name;
};

class Product {
public:
    Product(const Item * item) : _item(item) {
    }

    const Item * item() {
        return _item;
    }

    void setItem(const Item * item) {
        _item = item;
    }
private:
    const Item * _item;
};

int main() {
    QList<Item*> listOfNonConstItem;
    listOfNonConstItem.append(new Item("a"));
    listOfNonConstItem.append(new Item("b"));

    Product product(listOfNonConstItem.first());
    listOfNonConstItem.removeOne(product.item());

    return 0;
}

Unfortunately, the compiler fails:

/path/to/main.cpp:34:31: error: reference to type 'Item *const' could not bind to an lvalue of type 'const Item *'
    editableList.removeOne(pC);
                           ^~
/path/to/Qt/5.6.3/clang_64/lib/QtCore.framework/Headers/qlist.h:201:29: note: passing argument to parameter 't' here
bool removeOne(const T &t);
                        ^

I don't understand why there is a problem since removeOne() parameter is const.

Upvotes: 2

Views: 5413

Answers (1)

songyuanyao
songyuanyao

Reputation: 172934

You're confusing with const pointer and pointer to const.

What removeOne expects is the pointer(i.e. Item*); for the parameter declaration, const is qualifed on the pointer but not the pointee (i.e. Item* const &, reference to const pointer to non-const Item). While what you're passing is a pointer to const (i.e. const Item*), which can't be converted to pointer to non-const implicitly.

Changing the type of pC to Item* or Item* const would solve the issue.

Upvotes: 4

Related Questions