Let say I have a simple class hierarchy as follows with a common api:
#include <memory>
class Base {
public:
void api() {
foo();
}
protected:
virtual void foo() {
std::cout << "Base" << std::endl;
}
};
class FirstLevel : public Base {
protected:
virtual void foo() {
std::cout << "FirstLevel" << std::endl;
}
};
when I use the base class pointer I get the correct dispatch as follow:
std::shared_ptr<Base> b = std::make_shared<Base>();
std::shared_ptr<Base> fl = std::make_shared<FirstLevel>();
b->api();
fl->api();
Which correctly prints :
Base
FirstLevel
However when I use the base class reference the behavior is unexpected:
Base &b_ref = *std::make_shared<Base>();
Base &fl_ref = *std::make_shared<FirstLevel>();
b_ref.api();
fl_ref.api();
which prints:
FirstLevel
FirstLevel
Why is the dispatch different when using references as opposed to pointers?
std::shared_ptr
created bymake_shared()
cease to exist at the end of the expression, which also destroys the object they contain. Bothb_ref
andf1_ref
therefore are dangling references. Using them then causes undefined behaviour.