문제

Example, I have a CarPool class that creates lots of Car objects. It stores them in a vector<Car*> all_cars_;

The Car class is actually a base type of many different types of cars (so a vector<Car> would not work as I understand it).

I have some Person objects that may have access to some of these cars. The Person class stores them in a vector<Car*> my_cars_;.

The CarPool object will always outlive the Person objects and so is responsible for the ownership. Because of this I was thinking about making the CarPool collection into vector<unique_ptr<Car>> all_cars_;

Should I update the Person classes at all? If so, what should the all_cars_ collection hold? Or should they remain as old-school pointers? Are old-school pointers still a 'modern' way of referring to objects?

도움이 되었습니까?

해결책

vector<unique_ptr<Car>> all_cars_;

sounds ideal for your application. Whoever owns all_cars, then also owns all of the Car*s in all_cars. And this will be superior to:

vector<Car*> all_cars_;

for at least 2 reasons:

  1. you won't have to worry about the memory ownership code any longer.
  2. The compiler will keep you from accidentally having more than one entity own any of the pointers in all_cars_.

For:

vector<Car*> my_cars_;

it sounds like these are non-owning pointers. And so keeping them as Car* is perfectly reasonable. This also allows you to freely make copies of any of these pointers. The only thing you'll need to watch out for is the invalidation of the pointers due to changes in all_cars_, which you are surely already managing with your current design.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top