so i understand that the delete keyword can only be used when something has been declared with the new keyword. so i have a couple of question/
1) i heard that even if something is declared with the new keyword, it can only be deleted if it is a pointer. is that true? is it because you do not know the name of new object declared, thus a pointer is needed right? or can i delete anything that has been declared with new, without create a pointer?
2) so delete will not work on on anything else that is not declared with new? are therere exceptions?
3) normal variables, objects, and values and automatically deleted after a function or after its respective curly brackets?
if so how come i can do:
int me()
{
int u = 0;
while (u <5)
{
u++
}
cout << u;
}
it will cout 4 at the end? shouldn't it cout 0 since any changes to u are deleted after the curly brackets for the while loop ends?
3.)No, u was declared before the while loop. If you declared it in the while loop, then you should get a compiler error saying that u needs to be declared first.
It seems to me that you don't relly understand how dynamic memory works.
Here's a sample:
1 2 3
int* ptr;
ptr = newint;
delete ptr;
(1) You don't declare something with new keyword. You first declare a pointer, then assign a value returned by operator 'new' to it. You cannot do this without pointers. (2) You can only 'delete' variables that were dynamically allocated, and the only way to handle such variables is with pointers.
(3) No, it is not deleted then. Memory doesn't get freed on every '}'. Only one the '}' that marks the scope in which it has been declared. Example:
1 2 3 4 5 6 7 8 9 10 11 12
int global_var; //never freed
int function(){
int apple;
if(1){
int banana;
}//banana deleted
while(1){
int candy;
apple++;//this will work
banana++;//and this will give you an error
}//candy deleted
}//apple deleted