Classes and use of 'New'

Started by
19 comments, last by alvaro 10 years, 3 months ago

  std::vector<std::shared_ptr<Car> > cars;

Looks ugly as sin* but provides fantastic functionality.

1) Deterministic destruction

2) No leaks

3) Exception safety

4) The pointer is guaranteed to remain the same even if the std::vector is resized. (i.e cars.at(7).get())

* Actually, the C# IDisposable pattern is much uglier when trying to get deterministic cleanup or resources.

If ownership is truly shared, this is the right thing to do. But the typical situation is that the container owns the data contained, and therefore std::vector<std::unique_ptr<Car>> is a better choice, and still hits all your checkpoints.

This topic is closed to new replies.

Advertisement