I would like to make a C++ class that maintains a polymorphic container. For example, a vet can hold a list of pets currently receiving treatment. If we use raw pointers, we could define a vet as follows.
class Vet{
std::vector<Pet*> pets;
public:
void addPet(Pet* pet);
};
We could add pets as follows.
Vet vet;
vet.addPet(new Dog{});
vet.addPet(new Cat{});
In this case, the destructor of Vet class should be made responsible for deleting the dynamically allocated pets maintained in pets
. To avoid this, I would like to use smart pointers. However, there are some issues which need clarification before I can correctly and cleanly implement such code.
Need help on following issues. Thanks in advance.
- Should I use
std::unique_ptr
orstd::shared_ptr
? or in which circumstances should I usestd::unique_ptr
orstd::shared_ptr
? or should I go back to using raw pointers? - If I choose to use
std::unique_ptr
what would be the method signature ofaddPet
method and its implementation?
- choice 1-1)
void addPet(std::unique_ptr<Pet> pet){
pets.push_back(std::move(pet));
}
- choice 1-2)
void addPet(std::unique_ptr<Pet>& pet){
pets.push_back(std::move(pet));
}
This choice only works if I construct a pet as follows.
std::unique_ptr<Pet> dog = std::make_unique<Dog>();
vet.addPet(dog);
- choice 1-3)
void addPet(PetType pet){
if(pet==PetType::Dog) pets.push_back(std::make_unique<Dog>());
//
}
- If I choose to use
std::shared_ptr
what would be the method signature ofaddPet
method and its implementation?
- choice 2-1)
void addPet(std::shared_ptr<Pet> pet){
pets.push_back(std::move(pet));
}
- choice 2-2)
void addPet(const std::shared_ptr<Pet>& pet){
pets.push_back(pet);
}