S
Squid Seven
I create a pointer to an item:
CardSession *cardSession;
Then, later, I use new to create an instance of the item and assign it
to that pointer:
cardSession = new CardSession();
In another function, I want to test if an object is assigned to that
pointer, and delete the object if that is so:
if( cardSession )
delete cardSession;
I thought this would work, but then I discovered that, if cardSession
had *ever* been assigned a CardSession object with new, then the if
statement executes the delete command, even if the object had since been
deleted. Thus, I sometimes get an item doubly deleted with this code -
an undefined behavior that I think is causing my program to crash. Note
that if I have not yet used new in the program to assign an object to
cardSession, the if statement does not execute.
Could somebody explain this to me? Am I not understanding pointer usage
correctly, or is it innapropriate usage of new/delete? How can I do
this in an efficient fashion, without managing a global pointer to be
modified everytime I create or delete an object?
CardSession *cardSession;
Then, later, I use new to create an instance of the item and assign it
to that pointer:
cardSession = new CardSession();
In another function, I want to test if an object is assigned to that
pointer, and delete the object if that is so:
if( cardSession )
delete cardSession;
I thought this would work, but then I discovered that, if cardSession
had *ever* been assigned a CardSession object with new, then the if
statement executes the delete command, even if the object had since been
deleted. Thus, I sometimes get an item doubly deleted with this code -
an undefined behavior that I think is causing my program to crash. Note
that if I have not yet used new in the program to assign an object to
cardSession, the if statement does not execute.
Could somebody explain this to me? Am I not understanding pointer usage
correctly, or is it innapropriate usage of new/delete? How can I do
this in an efficient fashion, without managing a global pointer to be
modified everytime I create or delete an object?