Anže Anže - 2 months ago 5
C++ Question

Deleting object from its member function

We have a

container
object and an
item
object.
Item
is part of the
container
. The
item
member function calls
container
function which deletes the
item
.

What happens when
container
function that deleted
item
object returns to the
item
member function? It sounds like it leads to undefined behaviour. Is this a more elaborate case of
delete this;
?

edit:

class Item
{
Container* itemContainer;
std::string itemName;

void check(void)
{
bool condition = false;

// check some condition (not relevant to the question)

if (!condition)
{
itemContainer->CheckFailed(itemName);
}
}
}

class Container
{
std::vector<Item*> itemList;
void checkFailed(std::string)
{
Item* targetItem;

//find item by name

delete targetItem;
}
}


So my question was: what happens if
condition
is false and
checkFailed
from
Container
is called (
targetItem
is the
item
from where the
Check()
function is called).

Answer

The behaviour is well defined (or not undefined).

More specifically, the behaviour is well-defined if the object was created with operator new, and is not used after being deleted (e.g. a [now dangling] pointer to it is dereferenced, a non-static member is accessed, a non-static member function called, etc).

If the object is used after being deleted, then the behaviour is undefined.

Comments