mardi 24 décembre 2019

Why can I mutate member variable in a const object which is the result of a returning const object function?

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?

Aucun commentaire:

Enregistrer un commentaire