Reputation: 179
I've read some answers in SO and tutorials in other places that generally give the following idea:
Reference variables can be used as a second name or an alias for another variable
Is that indeed true or are there situations where it is either not possible or not convenient to do so? When is it viable and how to make it so?
The motivation for my question:
I followed this notion inside variables of a class and ended up with a problem whenever objects of those classes were copied (The references inside the copied objects would refer to the original variables). The solution I've seen so far involves specifying a custom copy constructor to change the initialization of those aliases from the default, which can be a lot of work since you can't extend the default constructor to change those specific variables and you are then required to write one for your entire class or for a nested one that wraps your aliases ( and thus also limits the names you can use).
Bottom-line, as far as I know, using reference member variables as aliases is either unsafe (it won't work as expected if your variable is copied) or not easy( you may have to write and maintain a lot of code).
Having said that, my question can be split as follows:
Upvotes: 2
Views: 115
Reputation: 69884
References are safe when:
That's it.
Examples of this are:
A. Parameters to a function which will not store the references anywhere.
B. Aliasing a deeply nested or computed element in a container to make code cleaner.
C. Inside a functor that has temporary lifetime (such as a custom printer object)
At almost Any other time you should either be using a copy or a shared pointer.
Upvotes: 2