gcc/clang "passing const X as this discards qualifiers" in CI
Calling a non-const member function on a const object would let it modify the object. The compiler refuses because the call discards the const qualifier on this.
What this error means
A method call on a const reference or const member fails with "discards qualifiers", typically when the called method is not marked const.
gcc
app.cpp:11:14: error: passing 'const Buffer' as 'this' argument discards qualifiers [-fpermissive]
11 | return b.size();
| ~~~~~~^~
note: in call to 'int Buffer::size()'Common causes
How to fix it
Mark read-only methods const
- Add const to member functions that do not modify the object.
- This makes them callable on const objects and references.
gcc
class Buffer {
public:
int size() const { return len_; } // const-qualified
};How to prevent it
- Const-qualify every member function that does not mutate the object so const instances can call it.
Related guides
gcc/clang "cannot bind non-const lvalue reference to an rvalue" in CIFix gcc/clang "cannot bind non-const lvalue reference of type X& to an rvalue" in CI - a temporary is passed…
gcc/clang "use of deleted function" in CIFix gcc/clang "use of deleted function" in CI - code calls a function explicitly deleted or implicitly delete…