使用boost :: scoped_ptr来存放引用时,不会调用派生对象的析构函数。它使用boost :: shared_ptr。为什么boost :: scoped_ptr在继承方案中不起作用?
#include "stdafx.h"
#include <iostream>
#include "boost/scoped_ptr.hpp"
#include "boost/shared_ptr.hpp"
using namespace std;
class Base
{
public:
Base() { cout << "Base constructor" << endl ; }
~Base() { cout << "Base destructor" << endl; }
};
class Derived : public Base
{
public:
Derived() : Base() { cout << "Derived constructor" << endl; }
~Derived() { cout << "Derived destructor" << endl; }
};
int _tmain(int argc, _TCHAR* argv[])
{
boost::scoped_ptr<Base> pb; // replacing by shared_ptr does call Derived destructor
pb.reset(new Derived());
cout << "Program ends here" << endl;
}
你能解释一下吗?是否有一个“黄金法则”不使用scoped_ptr多态成员变量?
关于“为什么”的附加信息使得这是一个很好的答案。它提供了我需要的信息。谢谢! – Emile