Why can I expose private members when I return a reference from a public member function?

前端 未结 5 1761
[愿得一人]
[愿得一人] 2021-02-02 01:21

In the code snippet, I am able to access the private member variable outside the class scope. Though this should never be done, why is it allowed in this case? Is it a bad pract

5条回答
  •  攒了一身酷
    2021-02-02 02:00

    private does not mean "this memory may only be modified by member functions" -- it means "direct attempts to access this variable will result in a compile error". When you expose a reference to the object, you have effectively exposed the object.

    Is it a bad practice to receive a returned private variable by reference ?

    No, it depends on what you want. Things like std::vector::operator[] would be quite difficult to implement if they couldn't return a non-const reference :) If you want to return a reference and don't want clients to be able to modify it, simply make it a const reference.

提交回复
热议问题