Instead of
int *i = new int;
...
delete i;
could I just do this?
int i;
...
delete &i;
Instead of
int *i = new int;
...
delete i;
could I just do this?
int i;
...
delete &i;
You don't want to do that. The int declared on the stack will be cleaned up when the code goes out of scope.
Just do
int i;
After the closing brace for the code block the integer is declared in, it'll be removed from the stack anyway.
If you declare a variable on the stack, its destructor will be called and the memory reclaimed when it goes out of scope.
If you allocate space from a heap, you have to free that space explicitly.
You cannot mix these two strategies.
Short answer: no
Long answer:
int i;
declares a int on the stack. This int will be removed when the int falls out of scope.
int *i = new int;
declares an int pointer on the stack, then creates a int on the heap (the new) and assigns the address of the heap value to the stack value. Again, the int pointer is removed when it falls out of scope, but the heap value sticks around unless it's deleted.
If you want to allocate it on the stack, do this:
int i;
i=5;
The int will be remove when the stack will go out of scope (when you quit the function for instance).
If you want to allocate it on the heap, do this:
int* i = new int;
*i = 5;
delete i;
This will create you a pointer to a int on the heap. Delete it when you don't need it anymore.
You should only dynamically allocate variables if you need them on the heap.
A common misconception (or habit) from people who program in other languages, such as java, is to use the new
operator to create every variable. This is not necessary and may cause fragmentation in your code.
In C++, for small variables, just declare them:
int i;
instead of:
int * i = new int;
By not declaring them using the new
operator, you are allowing the compiler to automatically dispose of them when necessary (a.k.a. when leaving scope). This saves the burden of allocation and deallocation from the programmer.
No. In fact, NO! You can only use delete
to free memory that was allocated by new
. If you call delete
on a pointer to a local variable, or a pointer to memory allocated by malloc()
, your program will likely crash.
Also, be sure to understand the difference between delete
and delete []
.
Not to mention that there is no need to delete a local variable. It is allocated on the stack, and will be destroyed automatically when it goes out of scope (e. g. when the function returns).
Don't do this
int i;
...
delete &i;
But if You really must allocate an int on the heap and You absolutely want your variable to look like a normal int variable, You could try this:
int &i = *(new int);
...
delete &i;