Mannaggia
Mannaggia

Reputation: 4819

C++: reference and lifetime extension using const

This refers to the C++ programming language. Assume we have a class C and do this:

C var1 = C(init_parameters);

C& var2(var1); 

Question 1: If we change var2, for example var2.memberA = 3, is this affecting also var1? Or did we create a new object so that var2 is not referencing var1?

Question 2: Assume we have a function like this:

const C& f(C var1) {
  const C& tmp(var1);
  return tmp;
}

Can we now call the above function, e.g. value = f(var1) and get a valid reference value? In principle the return reference is out of scope but is the const extending the lifetime? What happens if var1 is modified or deleted, does this affect the constant reference value? In other words and for the sake of clarity, can I use the variable value as if it was a copy of var1?

Upvotes: 0

Views: 508

Answers (1)

LogicStuff
LogicStuff

Reputation: 19607

C& var2(var1); and const C& tmp(var1); do not call any special member functions. You're declaring references - aliases for the referenced objects/variables (yes, changes made to var2 are actually made through var2 to var1).

Concerning lifetime extension, that applies to binding rvalues to const&. var1 is an lvalue and its lifetime is fixed to its scope.

To the second example, you can't return a reference (even to const) to a local variable. An alias doesn't change that. All that the caller will get is a dangling reference.

Upvotes: 2

Related Questions