First, let me re-iterate: the biggest issue is not one of lifetime, but one of encapsulation.
Encapsulation does not only mean that nobody can modify an internal without you being aware of it, encapsulation means that nobody knows how things are implemented within your class, so that you can change the class internals at will as long as you keep the interface identical.
Now, whether the reference you return is const
or not does not matter: you accidentally expose the fact that you have a Mother
object inside of your Family
class, and now you just cannot get rid of it (even if you have a better representation) because all your clients might depend on it and would have to change their code...
The simplest solution is to return by value:
class Family {
public:
Mother mother() { return _mother; }
void mother(Mother m) { _mother = m; }
private:
Mother _mother;
};
Because in the next iteration I can remove _mother
without breaking the interface:
class Family {
public:
Mother mother() { return Mother(_motherName, _motherBirthDate); }
void mother(Mother m) {
_motherName = m.name();
_motherBirthDate = m.birthDate();
}
private:
Name _motherName;
BirthDate _motherBirthDate;
};
See how I managed to completely remodel the internals without changing the interface one iota ? Easy Peasy.
Note: obviously this transformation is for effect only...
Obviously, this encapsulation comes at the cost of some performance, there is a tension here, it's your judgement call whether encapsulation or performance should be preferred each time you write a getter.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…