使用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