which never releases the 4 bytes used. |
Pointers are variables too.
They are like
long unsigned int's which hold a number (the number being a memory address).
Depending on the computer type, pointers can use 4 or 8 bytes (32-bit and 64-bit should ring a bell).
So yes,
delete'ing the pointer would release 4 bytes of memory for the
int.
But the 4 or 8 bytes required for the pointer itself would still be used.
Local variables live in a part of memory called the stack.
Whenever a function is called, it allocates space for its local variables on the stack.
When the function returns, it deallocates the space. All of this happens automatically.
(This is a simplified explanation, more technically a stack pointer (I think) is being constantly changed.)
http://en.wikipedia.org/wiki/Call_stack
Now going back to the pointers... they can be used for dynamic memory allocation but in modern C++ you shouldn't.
If you need a dynamically allocated array, C++ gives you
std::vector.
If you need a pointer to a function, C++11 gives you
std::function.
If you need a pointer + dynamic allocation for polymorphism, C++11 gives you
std::unique_ptr.
std::unique_ptr is a smart pointer.
Smart pointers behave like regular pointers, except they automatically
delete the memory when they go out of scope. So you no longer need to manually
delete anything.
1 2 3 4 5 6 7 8
|
#include <memory>
// ...
std::unique_ptr<int> smart_pointer(new int);
*smart_pointer = 4;
std::cout << *smart_pointer << '\n';
|
So for a lot of things you'd use pointers for, C++ offers better alternatives.
You'll end up using pointers when you write your own data structures, for example trees, where parent nodes link to their children nodes via pointers and there's no other way.