Reputation: 59
I'm trying to make sure my code is free of memory leaks. I have some items of a custom class and a box-class containg pointers to these items.
struct Item{int x;};
struct Box{ vector<Item*>; };
item_1 = new Item{5};
item_1 = new Item{7};
Box* b = new Box{vector<Item*> {item_1, item_2}};
//When it's time to clear memory
delete b;
delete item_1;
delete item_2;
I'm curious about the vector of pointers here. Is it stored on the heap too? And does it get deleted in the above example? And what would be the best way to write proper constructors/destructors for 'Box', in this case?
Upvotes: 0
Views: 58
Reputation: 75688
Your code is absolutely not free of memory leaks. Any exception will cause your code to leak memory. That's why in C++ we have RAII.
In C++:
new
/delete
in user codeBox b = Box{...}
std::unique_ptr
)and what would be the best way to write proper constructors/destructors for 'Box', in this case?
The proper way to write constructors/destructors is to not write copy/move constructors and destructor. However if Box
is polymorphic then you must make the destructor virtual: virtual ~Box() = default;
Upvotes: 3