Damir Tenishev
Damir Tenishev

Reputation: 3342

How std::shared_ptr avoids completeness requirement for holding object?

How exactly std::shared_ptr handles incomplete type while std::unique_ptr can’t although they both have to deal with destruction of the holding object this way or another?

This code compiles just fine:

#include <memory>

class Somewhere;

struct C {
    std::shared_ptr<Somewhere> here;

    virtual ~C() = default;
};

int main()
{
    C c;
}

And if you replace std::shared_ptr with std::unique_ptr it won’t because the latter requires the holding type to be complete. I read explanations for this here, here, here and here and they say the same things that difference is in completeness requirements with nice clues for reasoning like “The reasons are obscure, having to do with a dynamic deleter vs a static deleter.”.

My assumption is that std::unique_ptr has to delete the object directly, owning it and std::shared_ptr somehow uses underlying level to place the destructor at the same module where std::make_shared where invoked and where the complete type exist because it needs to be created. And here comes the clue (The reasons are obscure, having to do with a dynamic deleter vs a static deleter) from above.

Anyway, looking into implementation of std::shared_ptr (MSVC version), I can’t see the way they handle it.

To put in a nutshell, the question is, in case the internal counter of std::shared_ptr drops to zero and it has to destruct the holding object, how it handles this it this specific pointer instance declared in the place where complete definition of holding object is inaccessible? How would it call the correct destructor?

Upvotes: 0

Views: 77

Answers (0)

Related Questions