TartanLlama / expected

C++11/14/17 std::expected with functional-style extensions

Home Page:https://tl.tartanllama.xyz

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is there a way to enforce a shared pointer copy, and never a move?

aneksteind opened this issue · comments

I'm using tl::expected<std::shared_ptr<MyType>, MyError> and want to ensure that the pointer is never moved, and only copied (for thread safety reasons). Is there something I can do about my type to enforce this so that I can work with the pointer in a thread-safe manner in other locations outside of the expected object? I'm running into a scenario where I believe the reference count is getting decremented elsewhere (in a library I don't control) while the pointer is getting moved by expected when I create the object.

Specifically, I'm curious about the mechanics of tl::expected, and would like to avoid writing a wrapper class for std::shared_ptr that deletes the move constructor or something of similar effect. I would use a mutex, but don't have the ability to do so from within other libraries, only outside

following up, I believe the solution to my problem is to do

const std::shared_ptr<MyType> my_const_ptr {std::make_shared(...)};
tl::expected<std::shared_ptr<MyType>, MyError> my_expected = my_const_ptr;

thereby forcing a copy.

I don't think there is a thread safety issue with moving a shared pointer. The link doesn't suggest this either.
Can you be more specific as to what you think could go wrong?

You're right. What I was thinking about isn't really a concern -- the reference count should stay atomic in any case.