virtual deconstructor

virtual deconstructor

看看下面这个程序,如果我不在Base的析构函数加virual,那么vector析构时就不会调用D的析构了。这么简单多问题居然忘记了。


using namespace std;

class Base
{
public:
    Base(){};

    virtual ~Base()
    {
        cout << "~Base" << endl;
    }
};

class D : public Base
{
public:
    D(){};

    
    ~D()
    {
        cout << "~D" << endl;
    }
};


int main(int argc, const char * argv[]) {
    // insert code here...
    vector< unique_ptr< Base > > v;
    unique_ptr p( new D() );
    v.push_back( std::move( p ) );
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *