I always believed that temporary objects in C++ are automatically considered as const by the compiler. But recently I experienced that the following example of code:
It depends.
int f();
const int g();
class C { };
C x();
const C y();
In the case of both f()
and g()
, the returned value is not const because there are no const-qualified rvalues of non-class type. The const
in the return type of g()
is completely useless (in fact, it's worse than useless, since it can in rare circumstances cause issues with template instantiation).
In the case of x()
, the returned value is not const (because it isn't const-qualified). In the case of y()
, the returned value is const (because the return type is const-qualified). The const
qualifier here (or lack thereof) is meaningful because the return type is a class type.