Two questions:
Is it correct to create a dynamic variable with the
static
specifier?static int *i = new int;
- right?Can I work with din.variable after its removal:
int *i = new int; delete i; i = new int;
Yes, correctly, why not?
Yes you can. And in many libraries, something like this is done. You do not delete the variable i
, but release the memory pointed to by the pointer i
, and after that it can be forced to point to a new memory area.
Let's clear something up. int *i
is a variable of type pointer to int . When you write delete i;
you do not delete a variable, you delete what it indicates. In other words, you can do this:
int *i = new int; delete i; i = new int;
Because you are working with a variable of type pointer to int , which is whole and intact.
And so you can not do
int *i = new int; delete i; *i = 42;
Because you are working with an int variable that has been deleted.
Now that we have clarified this, everything automatically became clear with the first question. Yes, you can do that. You have created a static variable of type pointer to int , and initialized it with a pointer to a variable of type int , which is in dynamic memory
Source: https://ru.stackoverflow.com/questions/564980/
All Articles
i
in your examples is a regular pointer. It is not called and has never been called a “dynamic variable.” There is nothing "dynamic" ini
. A "dynamic variable" can be called what you select withnew
, but this variable has nothing to do withi
.i
simply points to this "dynamic variable", nothing more.delete i
does nothing withi
. - AnT