Jompa
Jompa

Reputation: 59

Constructing and deleting object containg vector of pointers

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

Answers (1)

bolov
bolov

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++:

  • never use explicit new/delete in user code
  • never user owning raw pointers
  • try and use objects instead of pointers to objects if that is possible. E.g. you can and should write Box b = Box{...}
  • when you do need owning pointers always use smart pointers (e.g. 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

Related Questions