C++ Logo

std-proposals

Advanced search

[std-proposals] std::shared_ptr resurrect

From: Valentin Palade <vipalade_at_[hidden]>
Date: Mon, 11 Dec 2023 14:00:17 +0200
Hello Everyone,

I would like your opinion on a small addition to the std::shared_ptr:

bool std::shared_ptr::resurrect();

with the following behavior:

   - will atomically decrement the use counter and
      - if use counter != 0 will reset the shared_ptr instance and return
      false
      - otherwise, increment the use counter, leave the shared_ptr instance
      unchanged and return true (thus resurrecting the shared_ptr instance).

Usage scenario:

   - producer creates a shared_ptr message to be sent to multiple consumers
   - threads/actors/connections
   - on consumers, we want to be able to return the shared_ptr message to
   the producer (e.g. to be reused), once consumed by all.

Code sample:
using SharedMessageT = std::shared_ptr<Message>;
std::promise<SharedMessageT> p;
auto f = p.get_future();

vector<jthread> thr_vec;
{

    auto sm = std::make_shared<Message>();

    auto lambda = [&p, sm]() mutable {
        doConsume(*sm);

        if (sm.resurrect()) {
            p.set_value(std::move(sm));
        }
    };

    for (size_t i = 0; i < 4; ++i) {
        thr_vec.emplace_back(lambda);
    }

    if (sm.resurrect()) {
        p.set_value(std::move(sm));
    }
}
{
    auto sm = f.get();
    doReuse(sm);
}


Similar concept implemented here:
https://github.com/solidoss/solidframe/blob/a54ef124ac77c97689c5d9204be35936aaf85c26/solid/utility/sharedbuffer.hpp#L139
And tested here:
https://github.com/solidoss/solidframe/blob/a54ef124ac77c97689c5d9204be35936aaf85c26/solid/utility/test/test_shared_buffer.cpp#L36

Thanks,
Valentin Palade

Received on 2023-12-11 12:00:30