Returning `const bool` triggers warning C4180

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

Warning 1 warning C4180: a qualifier applied to a function type does not have that is;

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

The following code will not lead to the same warning instead.

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

Question1 Is it true that using const Fundamental_Data_Types as the return value of a function does not make sense?

Question2 Is it true that using const Type as the return value of a function makes sense if Type is a / struct class?

thanks

// 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 } 
+6
source share
1 answer

Yes and yes for both of your questions. The return values ​​of rvalues ​​and cv qualifiers apply only to r values ​​if they are of class type.

The reason for this is quite simple: usually there is nothing you can do with rvalue, where the constness difference is the value, after all, and not the object. With a class type, there are member functions that (which means you can get an lvalue from an rvalue), so the constant suddenly becomes relevant.

+7
source

Source: https://habr.com/ru/post/948947/


All Articles