struct Dummy {
int a = 2;
int b = 6;
const Dummy share() {
return Dummy{};
}
};
There is a member function called share()
which returns a const Dummy
object in the Dummy
structure above. I except that I can't mutate the object returning from the share()
function.
However, the result showed that the object is mutable. I paste experimental code below for more details.
int main() {
Dummy d1;
auto d2 = d1.share();
d2.a = 10;
// the output is 10.
std::cout << "d2.a is " << d2.a << std::endl;
}
So why can I mutate member variable in this const object?
Using "auto" resolves to "Dummy", not "const Dummy". Thus, d2 is (formally) copy-constructed from the result of share, and it can be modified. You can force d2 to be immutable (independent of the return type of share) by saying "const auto".
In particular, the inference performed by "auto" drops the outermost layer of const/volatile qualifiers if they exist, as explained in this other question: CV - qualifiers of an auto variable