IFeel3 IFeel3 - 17 days ago 5
C++ Question

Destructor of class with vector of shared_ptr causes error

I have a class Animal which is base class for few different Animals and a class Herd which stores shared_prt to animals in a vector. I'm unfamiliar with smart pointers but I had to use them in my code in orded to handle inheritance. It seemed to work fine but after my code gets to the destructor of "Herd" it throws an error.
What's wrong with it?

class Animal {
public:
Animal(string _sound) :
sound(_sound) {}
void give_sound() {
cout << sound << " ";
}
bool operator==(Animal arg) {
return (typeid(*this).name() == typeid(arg).name());
}
protected:
string sound;
};

class Dog : public Animal {
public:
Dog() : Animal("woof") {}
};

class Cat : public Animal {
public:
Cat() : Animal("meow") {}
};

class Cow : public Animal {
public:
Cow() : Animal("moo") {}
};

class Herd {
public:
Herd() {}
~Herd() {
vec.clear();
}

Herd operator+(Animal *arg) {
shared_ptr<Animal> ptr(arg);
vec.push_back(ptr);
return *this;
}

void operator+=(Animal *arg) {
shared_ptr<Animal> ptr(arg);
vec.push_back(ptr);
}


void make_noise() {
vector<shared_ptr<Animal>>::iterator v = vec.begin();
while (v != vec.end()) {
(*v)->give_sound();
v++;
}
cout << endl;
}

private:
vector<shared_ptr<Animal>> vec;
};

int main() {
Herd herd;
Dog d1, d2;
Cat c1, c2;
cout << "sound 1: " << endl;
herd.make_noise();
herd += &d1;
herd += &c1;
cout << "sound 2: " << endl;
herd.make_noise();
herd += &d2;
herd += &c2;
cout << "sound 3: " << endl;
herd.make_noise();
//herd = herd - &d1;
//herd = herd - &d2;
cout << "sound 4: " << endl;
herd.make_noise();
return 0;
}


edit: without vec.clear() it also crashes.

Answer
Dog d1, d2;
Cat c1, c2;

Those objects have automatic storage duration. They aren't meant to be managed be owning smart pointers.

The use case for smart pointers is heap allocation, for example:

herd += new Dog;
Comments