Here's a version of your code using unique_ptr. I added messages when something is constructed or destructed. I recommend you do this while you are learning this part of the language. If you do this in your earlier attempts, you'll see that your objects are not being destructed, and that's a problem.
#include <iostream>
#include <vector>
#include <string>
#include <memory>
struct Person {
Person(int p_age, std::string p_name)
: age(p_age + 4), name(p_name) {
std::cout << "Person constructed" << std::endl;
}
~Person() {
std::cout << "Person destructed" << std::endl;
}
int age;
std::string name;
};
std::ostream &operator<<(std::ostream &os, Person const &person) {
return os << "(age: " << person.age << ", name: " << person.name << ")";
}
struct Car {
Car(std::string p_model, std::unique_ptr<Person> p_owner, std::unique_ptr<Person> p_driver)
: model(p_model), owner(std::move(p_owner)), driver(std::move(p_driver)) {
std::cout << "Car constructed" << std::endl;
}
~Car() {
std::cout << "Car destructed" << std::endl;
}
std::string model;
std::unique_ptr<Person> owner;
std::unique_ptr<Person> driver;
};
std::ostream &operator<<(std::ostream &os, Car const &car) {
return os << "(model: " << car.model << ", owner: " << *car.owner << ", driver: " << *car.driver << ")";
}
int main() {
std::vector<std::unique_ptr<Person>> people;
people.push_back(std::make_unique<Person>(55,"Phil"));
people.push_back(std::make_unique<Person>(61,"Sylvia"));
people.push_back(std::make_unique<Person>(65,"Jeff"));
std::vector<std::unique_ptr<Car>> cars;
cars.push_back(std::make_unique<Car>("F-100", std::make_unique<Person>(57,"Phil"), std::make_unique<Person>(59,"Jeff")));
for (auto const &p : people)
std::cout << *p << std::endl;
for (auto const &c : cars)
std::cout << *c << std::endl;
}