S
S
sddvxd2018-11-25 22:26:05
C++ / C#
sddvxd, 2018-11-25 22:26:05

When will const, an alias in a function, be removed?

Good afternoon!

void func(int&); //Увеличить на 1 входящее значение
//...
func(1); //Попытка инициализировать ссылку, которая сразу же станет "битой"

I agree with the compiler - really nonsense is written, but after reading the book I found the order of alias initialization:
  1. First, if necessary, a type conversion is applied (in our case int(1))
  2. then the value is placed in a temporary variable
  3. finally, the address of this variable is used as an alias (reference) initializer

It turns out that the memory for int (1) is allocated first, everyone could live happily, but the object must be deleted immediately (since it is temporary). And therefore the compiler forces to describe an alias as a constant. It also says that if we do this:
void func(const int&); //Увеличить на 1 входящее значение

Then there will be no problems with the constant and nothing will be deleted. The essence of the question: if a temporary object is not created in this case, then how long will const int & live in the function and why the expression has permission to compile
const double& d = 1;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2018-11-26
@sddvxd

This feature is called extending the life of temporary objects when they initialize a constant reference.
Details: https://herbsutter.com/2008/01/01/gotw-88-a-candid...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question