question about delete keyword

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.
Last edited on
closed account (jwC5fSEw)
1) new always returns a pointer, by definition.

2) delete is only for deallocating memory allocated by new, so there wouldn't be any point if it could be used on other objects.

3. u was declare in the scope of me(), not in the while-loop, so any changes to u in the while-loop will remain in the scope of me().
It seems to me that you don't relly understand how dynamic memory works.
Here's a sample:
1
2
3
int* ptr;
ptr = new int;
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 
ight thanks.
Topic archived. No new replies allowed.