Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return of `const bool` causes warning C4180 [duplicate]

Tags:

c++

struct CCompare
{
    const bool operator()(const int& lhs, const int& rhs) const {
        return lhs < rhs;
    }
};

Warning 1 warning C4180: qualifier applied to function type has no meaning;

I saw the usage with return value as const bool in a programming book. When I compiled the above code with vs2010, it reports the warning C4180.

The following code instead will not cause the same warning.

struct CCompare
{
    bool operator()(const int& lhs, const int& rhs) const {
        return lhs < rhs;
    }
};

Question1> Is it true that the usage of const Fundamental_Data_Types as a function returned value doesn't make sense?

Question2> Is it true that the usage of const Type as a function returned value only makes sense iff the Type is a class/struct?

Thank you

// Update //

struct CClass
{
    int val;
    CClass(int _val) : val(_val) {}

    void SetValue(int _val) {
        val = _val;
    }
};

struct CCompare
{
    const CClass getMe() const {
        return CClass(10);
    }

    CClass getMeB() const {
        return CClass(10);
    }
};

int main(/*int argc, char *argv[]*/) 
{
    CCompare c;

    c.getMe().SetValue(20);   // error
    c.getMeB().SetValue(20);  // ok
}
like image 328
q0987 Avatar asked Jul 08 '13 14:07

q0987


1 Answers

Yes and yes to both of your questions. Return values are rvalues, and cv-qualifiers only apply to rvalues if they have a class type.

The reason for this is fairly simple: there's normally nothing you can do with an rvalue where const-ness would make a difference—it's a value, after all, and not an object. With a class type, there are member functions to take into account (which means that you can get an lvalue from the rvalue), so const-ness suddenly becomes relevant.

like image 111
James Kanze Avatar answered Sep 18 '22 10:09

James Kanze