19172281
19172281

Reputation: 237

Alternative to returning pointer or reference to private member

I often see people returning pointers or references to private members, which I've been told is bad practice (I've been guilt of doing this myself). What kind of poor design decisions lead to this, and what safe alternatives are there, if any?

Upvotes: 0

Views: 337

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Returning a reference to private members is a bad idea only when the reference is mutable. This presents a problem, because callers obtain means for modifying the state of your object, bypassing any consistency checks that you may have in place.

Although returning a const reference does not expose you to the same problem, it is still not ideal, because the lifetime of the object that you returned is controlled by your object. If you decide to de-allocate the member while the caller still has a reference to it, you may cause undefined behavior in the caller.

A viable alternative to returning a reference is returning copies. This works reasonably well for small objects, but for larger objects it is still problematic. You could return a const reference with clear explanations of its lifetime, or return a smart pointer.

Upvotes: 2

Related Questions