mardi 28 juin 2016

Alternatives to refcount for unique_ptr

In following code example, there should be exist one instance of struct A inside struct B as long as any object of B is living. Example works as expected.

#include <memory>
#include <iostream>
#include <mutex>

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

struct B
{
    B()
    {
        std::cout << "B() called" << std::endl; 

        std::lock_guard<std::mutex> guard(mtx);
        if( !refCount )
        {
            a.reset( new A ); 
        }
        ++refCount;
    }

~B()
    {
        std::cout << "~B() called" << std::endl;
        std::lock_guard<std::mutex> guard(mtx);
        --refCount;
        if( !refCount )
        {
            a.reset( ); 
        }
    }

    static std::unique_ptr<A> a;
    static std::mutex mtx;
    static int refCount;
};

std::unique_ptr<A> B::a;
int B::refCount(0);
std::mutex B::mtx;

int main()
{
    {
        B b1; //B::a should be created here
        B b2;
    } //B::a should be destroyed here

    B b3; // B::a should be recreated here
} //B::a should be destroyed again here

See also http://ift.tt/290j5gf

My question: Is there an alternative (threadsafe!) implementation without a refcount? Is this maybe possible to solve with a construct of std::shared_ptr and std::weak_ptr?

Aucun commentaire:

Enregistrer un commentaire