我有一個類動物是幾個不同的動物的基類和一個類牧羣存儲shared_prt動物的向量。我不熟悉智能指針,但是我不得不在我的代碼中使用它們來處理繼承。它似乎工作正常,但在我的代碼到達「Herd」的析構函數後,它拋出一個error。 它有什麼問題?類的矢量的shared_ptr的類的析構函數導致錯誤
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()它也崩潰。
在問題中發佈代碼。 – molbdnilo
@molbdnilo這裏是 – IFeel3
「*我不熟悉智能指針,但我不得不在我的代碼中使用它們來處理繼承。*」我有點困惑。由於對象是分配在堆棧上的,因此智能指針在這裏顯然不起作用。但是一個普通的啞指針應該工作得很好。爲什麼你認爲你需要智能指針? –