jeudi 27 juin 2019

Why is shared_ptr counter incremented when passed as const reference to base class?

Why is shared_ptr<drived> counter incremented when I pass it to a function that expects a const shared_ptr<base>&?

In this question one of the answers mentions:

shared_ptr<Base> and shared_ptr<Derived> are not covariant

I suspect that this is relevant to my question. What does it mean that they are not covariant?

Here is a code snippet to show case the scenario:

#include <iostream>
#include <memory>

class Base {};

class Derived : public Base {};

void f(const std::shared_ptr<Base>& x)
{
    std::cout << "in function expecting const shared_ptr<Base>& - Use count: " << x.use_count() << std::endl;
}

int main(int argc, char const *argv[])
{
    std::cout << "Base class" << std::endl;
    auto a = std::make_shared<Base>();
    std::cout << "Created shared_ptr:  Initial use count: " << a.use_count() << std::endl;
    f(a);

    std::cout << "------------------\nChild class" << std::endl;
    auto b = std::make_shared<Derived>();
    std::cout << "Created shared_ptr. Initial use count: " << b.use_count() << std::endl;
    f(b);

    return 0;
}

Results in:

>> g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
Base class
Created shared_ptr:  Initial use count: 1
in function expecting const shared_ptr<Base>& - Use count: 1
------------------
Child class
Created shared_ptr. Initial use count: 1
in function expecting const shared_ptr<Base>& - Use count: 2

Aucun commentaire:

Enregistrer un commentaire