有很多事情需要说。首先,我想知道下面的方法是否被认为是一种设计模式,甚至是一种常见的技术(这就是为什么我没有提供有关标题的更多信息)。如果是这样的话,那叫什么名字?无论如何,这是我试图实现的缩小版本。由于我需要使用复制,我发现使用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
你也错过了虚拟析构函数。 –