3

Consider the code below:

#include <iostream>
#include <memory>

struct Base
{
    ~Base() {std::cout << "~Base()" << std::endl;}
};

struct Derived : Base
{
    ~Derived() {std::cout << "~Derived()" << std::endl;}
};

int main()
{
    // why does the right destructor is called at program exit?
    std::shared_ptr<Base> sptrBase{std::make_shared<Derived>()}; 
}

which outputs

~Derived()

~Base()

My Base class doesn't have a virtual destructor. However, when using a Derived object via a smart pointer to Base, the correct ~Derived() destructor seems to be correctly invoked at program exit. Why does this happen (instead of undefined behaviour)? Is it because the Derived type is somehow "recorded" when the result of std::make_shared<Derived>() is converted into std::shared_ptr<Base>? Or is it plain UB?

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • What do you mean "instead of undefined behaviour"? By definition undefined behavior can be anything, including what you see. – Adam May 08 '15 at 04:35
  • @Adam I should actually ask if this is UB or not. – vsoftco May 08 '15 at 04:35
  • 1
    roughly speaking, `shared_ptr` contains a function pointer to the destructor, which is set correctly by `make_shared` – M.M May 08 '15 at 04:35
  • @MattMcNabb so the default deleter takes care of correct deletion? – vsoftco May 08 '15 at 04:36
  • Yes, because `make_shared` creates a default deleter for Derived, not Base – M.M May 08 '15 at 04:37
  • @MattMcNabb ok, it was simpler than I though... I forgot that there is one more object involved, which is the deleter. Thanks! You should post an answer and I'll gladly accept it. – vsoftco May 08 '15 at 04:38
  • My question is indeed a dupe (saw this now), but probably of this question: http://stackoverflow.com/q/3899790/3093378. I nominated the question for reopening so it can be closed under this dupe. Or, if someone can change the dupe, please do, as I think it's a better fit. – vsoftco May 08 '15 at 04:45
  • I am curious, I copy / pasted this code and received errors. I am on a Mac and tried updating GCC to version 4.9.2 (to attempt compiling) but it still does not compile. The number of errors I get is too large for a comment, but this is the first one: `foo.cpp: In function 'int main()': foo.cpp:17:5: error: 'shared_ptr' is not a member of 'std' std::shared_ptr sptrBase{std::make_shared()}; ^` – asimes May 08 '15 at 05:13
  • @asimes compile with `-std=c++11` – vsoftco May 08 '15 at 05:23

0 Answers0