有很多事情需要說。首先,我想知道下面的方法是否被認爲是一種設計模式,甚至是一種常見的技術(這就是爲什麼我沒有提供有關標題的更多信息)。如果是這樣的話,那叫什麼名字?無論如何,這是我試圖實現的縮小版本。由於我需要使用複製,我發現使用std :: shared_ptr最好避免釋放(刪除)指針。繼承和智能指針(std :: shared_ptr)
class Foo
{
public:
Foo() : ptr(nullptr) {}
Foo(const Foo& foo) : ptr(foo.ptr) {}
virtual ~Foo() = default;
void whatever() {
if (ptr)
ptr->whateverHandler();
}
void reset() {
ptr.reset();
}
void resetBar() {
ptr.reset(new Bar);
}
// Other resets here...
protected:
Foo(Foo* foo) : ptr(foo) {}
private:
// Every child class should override this
virtual void whateverHandler() {
throw "whateverHandler cant be called within base class";
}
protected:
std::shared_ptr<Foo> ptr;
};
class Bar : public Foo
{
public:
Bar() : Foo(this) {}
void whateverHandler() {
printf("Bar's handler!!! \n");
}
};
這一切看起來不錯,編譯好,但是,下面的exame崩潰。這是爲什麼?
int main()
{
{
Foo f;
f.resetBar();
}
return getchar();
}
當一個Bar被銷燬時,它的Foo被銷燬兩次 – Danh
你可能需要'std :: enable_shared_from_this'。但是,在這個特定的例子中,你不需要它,要麼 – Danh
你也錯過了虛擬析構函數。 –