guivenca
guivenca

Reputation: 179

When can reference variables be safely and easily used as aliases?

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:

  1. Can member reference variables be used as aliases without all the trouble mentioned earlier?
  2. Are there any other situations where they can be unsafe? ( besides in copy operations)
  3. When you don't have a member reference variable, can you indeed safely use them as a second name or is there a situation where extra care should be taken?

Upvotes: 2

Views: 115

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69884

References are safe when:

  1. What they are referencing cannot go away before the reference goes out of scope.

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

Related Questions