U
U
user1082022-01-10 11:03:07
C++ / C#
user108, 2022-01-10 11:03:07

What is the point of defining const int &ref=1;?

What is the meaning of the definition: What is it for and how does it work?
const int &ref=1;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Shatunov, 2022-01-10
@user108

To get started, it's worth going over the categories of expressions in modern C++ a bit.
From the article it will be seen what 1has the prvalue category. 1is a literal and is not a string literal. This is a literal with a intdefault type.
If you turn to the article again and look at the prvalue properties, you will see, in particular, that the prvalue:

  • always have full type;
  • do not have a location, and therefore do not have an address in memory;
  • can be used to initialize cvq-lvalue-ref and rvalue-ref .

The last point says that the code const int& ref = 1;or int&& ref = 1;is completely standard.
refin this case will refer to the passed literal and the lack of placement of the literal is not a hindrance to this.
The point of such expressions is to allow such code to be written.
void foo( const int& ref );

void bar()
{
  foo( 1 );
}

Washed away specifically code const int &ref=1;can be found in not writing magic constants in the code. ref- a very bad name. But naked 1in code is even worse.
The software engineer writes his code not for the translator, but for his employees. The translator will understand any code and, based on any syntactically correct code, will always produce a working executable code. But other people in the code will be able to understand only when this code is written in an understandable way.
To make the code easier to understand, it is documented. Documentation is different. It can be comments, it can be a separate document. But code is best understood when it is "self-documented" [ 1 ], [ 2], i.e. when the code itself clearly explains the purpose of its existence and the principles of its work.
In order for the code to explain itself, the names of functions, variables and constants, the names of types and other handwritten constructs should reflect the purpose of their existence as clearly as possible. In particular, so that the code is not full of faceless magic numbers [ ? ], it is customary to denounce these numbers in the so-called. explanatory constants.
Such a constant can be defined as cvq-lvalue-ref , given a name that is understandable in the context of the code, and given the desired literal.

M
maaGames, 2022-01-10
@maaGames

For nothing. Moreover, it should not compile.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question