What is the difference between the two forms?
A pointer is a special variable that, instead of storing values, stores memory locations ... that is, points to other elements.
Thus, the following code:
int variable;
int* ptr = &variable;
what it does is that the pointer points to a specific variable ... if you modify the variable, the value pointed to by the pointer will also change and vice versa.
Instead, the following code:
int* ptr = new int;
What it does is, on the one hand, make a dynamic memory reservation and then modify the pointer so that it points to that memory.
What are the implications of one use and which of the other?
-
Variables have a specific scope. Outside of that scope, the variable simply does not exist and any pointer that points to the variable will become invalid (it will read garbage and write memory that it should not):
int* func()
{
int var;
int* ptr = &var;
*ptr = 5; // ok
return ptr;
}
int main()
{
int* ptr = func();
*ptr = 10; // peligro!!! ptr apunta a var que ya no existe
}
-
Dynamic memory does not have a defined life cycle but rather it is the algorithm itself that must free memory when it is no longer needed. In addition, the dynamic memory is usually much more abundant than the memory of the stack:
int* func()
{
int* ptr = new int;
*ptr = 5; // ok
return ptr;
}
int main()
{
int* ptr = func();
*ptr = 10; // ok
delete ptr;
}
When is this used and why / for what?
this
is an implicit pointer that only exists within classes and structures. When you write a code like this:
struct Test
{
int var;
void func()
{ var = 5; }
};
The compiler interprets it like this:
struct Test
{
int var;
void func()
{ this->var = 5; }
};
But when should we use this
?
It is necessary to use this
in those situations in which overlapping names occur. For example, in the following code:
struct Test
{
int var;
void func(int var)
{
var = 5;
}
};
What variable are we modifying? The variable member of the structure? The local variable of the function?
The answer is: the local variable of the function.
And how could the member variable be accessed? In this case it is when we have to use this
mandatorily:
struct Test
{
int var;
void func(int var)
{
this->var = var;
}
};
In the rest of the situations, its use is not obligatory. So it is relegated to the programmer's tastes, coding rules, ...