Modifying reference member from const member function in C++

后端 未结 3 1112
走了就别回头了
走了就别回头了 2020-12-06 03:57

I am working on const-correctness of my code and just wondered why this code compiles:

class X
{
    int x;
    int& y;
public:
    X(int& _y):y(_y)
         


        
3条回答
  •  执念已碎
    2020-12-06 04:59

    The situation is similar to pointer members. In a const member function, the const applies to the pointer itself, not the pointee.

    It's the difference between:

    X* const //this is how the const applies: you can modify the pointee
    const X*
    

    Except X& const isn't valid syntax, since the reference can't be made to refer to another object in the first place (they are implicitly always const). In conclusion: const on methods has no effect on member references.

提交回复
热议问题