0
典型的工廠設計模式要求基類聲明虛擬析構函數,但實際上可以使用shared_ptr
來避免這種情況。不含虛擬析構函數的多態的C++ shared_ptr
#include <iostream>
#include <memory>
#include <cstdio>
using namespace std;
class Dog {
public:
~Dog() { cout << "dog destroyed\n"; }
};
class Yellowdog : public Dog {
public:
~Yellowdog() { cout << "Yellow dog destroyed.\n"; }
};
class DogFactory {
public:
static shared_ptr<Dog> createYellowdog() {
return shared_ptr<Yellowdog>(new Yellowdog());
}
};
int main(int argc, char *argv[]) {
auto ptr = DogFactory::createYellowdog();
cout << ptr.use_count() << endl;
return 0;
}
在這種情況下,輸出是yellowdog destroyed
隨後dog destroyed
。但爲什麼?爲什麼使用shared_ptr
可以在~Dog
之前省略虛擬關鍵字?
由於用指針複製/傳輸的'Deleter'。 – Jarod42
因爲'shared_ptr'很神奇。 :-S –
更清楚的是,'Deleter'與delete(Yellowdog *)p;'類似。您將通過'return shared_ptr(new Yellowdog())獲得UB;'儘管如此。 –
Jarod42