does a "pair" which holds object needs to be deleted?

Viewed 257

I made a pair like this

typedef std::pair<int, Dish> OrderPair;

when Dish is an object. and I got a vector of OrderPair:

std::vector<OrderPair> orderList;

assuming that I want to delete one pair from the vector, does erase function is enough when I don't want to delete the dish from memory? I think the answer is yes, because creating a pair is not sitting in the heap, and therefore I don't need to release any memory. please tell me if I'm wrong.

2 Answers

When your OrderPair gets deleted, then the Dish that's part of it is also gone. When std::vector<OrderPair> orderList goes out of scope (end of the function it was declared in, etc.) then all the OrderPair within and thus all the Dish in there are also gone. When you erase an OrderPair using erase, then that Dish is gone.

does erase function is enough when I don't want to delete the dish from memory?

If you call erase, then that OrderPair and thus that Dish is gone from memory. If that's not what you want, you need a different data structure. For instance if OrderPair doesn't contain a Dish but a pointer to Dish, like this:

typedef std::pair<int, Dish*> OrderPair;

Then you could indeed erase that pair and the Dish isn't deleted from memory, just that one reference to it. But with just that small code snippet, it's hard to know your intentions.

Only objects that are explicitly allocated dynamically - using new or malloc, need to be explicitly deleted using delete or free. Heap memory is used for dynamic allocations.

In your case, you are pushing Dish object itself into the pair and not a pointer pointing to dynamic allocation.

>typedef std::pair <int, Dish> OrderPair;

So, the scope of the Dish object is bound to the scope of the pair object. When the pair in the vector is erased using erase method, the pair and with it the Dish object gets destroyed too.

Related