2012-03-02

shared_ptr vs inheritance

A picture is worth a thousand words

#include <iostream>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

class A: public boost::enable_shared_from_this<A>
{
public:
    typedef A Self;
    typedef Self Root;
    typedef boost::shared_ptr<Self> SPtr;

public:
    A(){ std::cerr << "DEBUG: A::A()" << std::endl; }
    virtual ~A(){ std::cerr << "DEBUG: A::~A()" << std::endl; }
    SPtr getSPtr()
    {
        return shared_from_this();
    }
};

class B: public A
{
public:
    typedef B Self;
    typedef A Base;
    typedef Base::Root Root;
    typedef boost::shared_ptr<Self> SPtr;

public:
    B(){ std::cerr << "DEBUG: B::B()" << std::endl; }
    virtual ~B(){ std::cerr << "DEBUG: B::~B()" << std::endl; }
    SPtr getSPtr()
    {
        return boost::dynamic_pointer_cast<Self>(Root::getSPtr());
    }
};

#define CHECKPOINT std::cerr << "CHECKPOINT: " __FILE__ " (" << __LINE__ << ")" << std::endl

int main()
{
    CHECKPOINT;
    A::SPtr spX(new A);
    CHECKPOINT;
    B::SPtr spY(new B);
    CHECKPOINT;

    return 0;
}

Compile!

g++ -W -Wall -Wextra -pedantic -Os shared_vs_inheritance.cpp -o shared_vs_inheritance

Run!

CHECKPOINT: shared_vs_inheritance.cpp (42)
DEBUG: A::A()
CHECKPOINT: shared_vs_inheritance.cpp (44)
DEBUG: A::A()
DEBUG: B::B()
CHECKPOINT: shared_vs_inheritance.cpp (46)
DEBUG: B::~B()
DEBUG: A::~A()
DEBUG: A::~A()

No comments:

Post a Comment