ブチッパーはすでにあなたに良いアドバイスをしました。ペットの寿命を正しく管理したい場合は、生のポインターの代わりにstd::unique_ptr<>
orを使用することを検討してください。std::shared_ptr<>
// the vector owns the pets and kills them, when they are removed
// from the vector
vector<std::unique_ptr<Mamal> > v1
// the vector has shared ownership of the pets. It only kills them,
// when noone else needs them any more
vector<std::shared_ptr<Mamal> > v2
// the vector has no ownership of the pets. It never kills them.
vector<Mamal*> v3
最後のケースでは、他の誰かがペットの死の世話をしなければなりません。ペットにそんなことしたくないですよね?
更新
ああ、言い忘れましたが、新しいものよりも優先するmake_shared()
かmake_unique()
、emplace_back()
代わりに使用する必要がありますpush_back()
v1.emplace_back(new Dog{Name, Blue, Owner});
v1.push_back(make_unique<Dog>(Name, Blue, Owner))
v2.emplace_back(new Dog{Name, Blue, Owner});
v2.push_back(make_shared<Dog>(Name, Blue, Owner))