jeudi 30 juillet 2015

Smart pointers' control block internal machinery

I'm wondering what are the exact conditions to release memory allocated for the internal control block shared by shared_ptr and weak_ptr.
I guess control block contains a shared_ptr counter and a weak_ptr counter.

#include <memory>
#include <iostream>

struct Dummy
{
    Dummy() { std::cout << "ctor" << std::endl; }
    ~Dummy() { std::cout << "dtor" << std::endl; }
};

int main()
{
    auto dummy = new Dummy();
    auto wp = std::weak_ptr<Dummy>(); // pointing to nothing

    {
        auto sp = std::shared_ptr<Dummy>(dummy); // 1
        wp = sp; // 2
    } // 3
    std::cout << "Land mark" << std::endl;
}

  1. Building a shared_ptr with dummy allocated memory. Control block is allocated, and it's Dummy pointer is set to "dummy"
  2. Building a weak_ptr from shared_ptr. Both smart pointers are sharing the same address of control block.
  3. Shared pointer is destroyed. Dummy dtor is called ("dtor" is printed before "Land mark"). Control block still lives until end of program.

Am I right about these comments ?
What happens (in details) within control block during these steps ?

Aucun commentaire:

Enregistrer un commentaire