I'm new here and glad to share this place with all of you =)
I have a question about new/delete :
Suppose I create two pointers of the same type, the first one with new and the second one without new. Then I assign the first one to the second one.
Then, can I use delete on the second one, even if it originally, was not created with new, but still equals a pointer that actually wascreatedwith new ?
Here's the simple code I think about:
_____________________________________________________
MyClass* first_ptr = new MyClass();
// it is stored in a global_vector:
global_vector.push_back(first_ptr);
//in a different block of the code
{
MyClass* second_ptr; // this one is not "created" with new
second_ptr = global_vector[0]; // for instance
delete second_ptr; // is this valid ?
}
I want the program to free the memory allocated during the creation of the first pointer, and the pointed object to be destructed.
Yes, this is perfectly legal (and in fact quite common).
delete doesn't delete the pointer, it deletes whatever the pointer points to. So if second_ptr and first_ptr both point to the same thing, then you can delete either one of them.
Once you do, though, both pointers will now be "bad pointers" since they point to deleted memory:
1 2 3 4 5
int* a = newint;
int* b = a;
delete b;
*a = 5; // EXPLODE ... this int has already been deleted