Suppose we have the hypothetical case where pointers are used for all types of variables. More exactly, we have the following procedure to read the elements of a one-dimensional array:
void leer_arreglo(int *&v)
{
int *i = new int;
for (*i = 0; *i < dim_v; (*i)++)
{
cout << "Elemento " << *i + 1 << ": ";
cin >> v[*i];
}
delete i;
}
As you can see, even the variable i
, which is only used to traverse the elements of the array, is declared as a pointer to int
, and as such, at the end of the procedure the memory must be manually released .
What would be the most reasonable solution for the variable i
to remain within the scope of the loop for
and at the same time avoid manually releasing the memory allocated for that pointer?
My first attempt was the one that follows:
void leer_vector(int *&v)
{
for (int *i = new int(0); *i < dim_v; (*i)++)
{
cout << "Elemento " << *i + 1 << ": ";
cin >> v[*i];
}
delete i;
}
The problem is that an error is generated at the moment of arriving at the delete i;
instruction since said variable no longer exists outside the scope of for
.
Then I came up with the following:
void leer_vector(int *&v)
{
for (int *i = new int(0); *i < dim_v; (*i)++)
{
cout << "Elemento " << *i + 1 << ": ";
cin >> v[*i];
delete i;
}
}
However, I have serious doubts that the above is a good idea because in each iteration I am releasing the assigned memory.
I did not really know what to do until I discovered the so-called smart pointers ( smart pointers , thanks Paula_plus_plus) and then I came to the following code:
void leer_vector(int *&v)
{
for (auto i = make_unique<int>(); *i < dim_v; (*i)++)
{
cout << "Elemento " << *i + 1 << ": ";
cin >> v[*i];
}
}
How nice, right? The variable i
is within the scope of for
and we do not have to worry about manually releasing the allocated memory. So, my question comes up: Is this a valid use of smart pointers?
I ask this question because despite reviewing some SO links where they are analyzed in which cases should be used this type of pointers, I still do not quite clear if in my particular case the last piece of code that I put is a correct and acceptable solution.
Thanks in advance for your comments and / or answers.