I want to have a unique_ptr
as a class variable to support polymorphism. I have the class built but I cannot use the std::vector
constructor because the std::unique_ptr
copy constructor is explicitely deleted. Here's an abstracted example:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Animal {
protected:
std::string noise = "None";
public:
Animal() = default;
virtual std::string getNoise() {
return noise;
}
};
class Duck : public Animal {
public:
Duck() {
noise = "Quack!";
}
};
class Dog : public Animal {
public:
Dog() {
noise = "Woof!";
}
};
typedef std::unique_ptr<Animal> AnimalPtr;
class Zoo {
public:
AnimalPtr animalPtr;
explicit Zoo(AnimalPtr animalPtr) : animalPtr(std::move(animalPtr)){};
explicit Zoo(const Animal& animal) : animalPtr(std::make_unique<Animal>(animal)){};
const AnimalPtr &getAnimalPtr() const {
return animalPtr;
}
};
int main() {
Zoo zoo1((Dog()));
Zoo zoo2((Duck()));
std::vector<Zoo> zoos = {zoo1, zoo2}; // error, Call to implicitly-deleted copy constructor of 'const Zoo'
return 0;
};
I could solve this problem by using a std::shared_ptr
instead, but something tells me this isn't the correct reason for allowing shared ownership. So my question is what is the correct way to solve this problem? (i.e. to allow me to construct a std::vector
of animal
s.