How to ensure a weak_ptr is not created from a temporary shared_ptr?

176 Views Asked by At

Let's have class Foo and method void use_weak_ptr(std::weak_ptr<Foo>). Is there a way to ensure - preferably at compile time - that the method is not called with temporary?

Allow this:

auto shared = std::make_shared<Foo>();
use_weak_ptr(shared);

Do not allow this:

use_weak_ptr(std::make_shared<Foo>());

Edit: Godbolt with suggestions.

1

There are 1 best solutions below

7
Passer By On BEST ANSWER

You "poison" overload resolution on rvalues

void use_weak_ptr(const std::shared_ptr<Foo>&&) = delete;
void use_weak_ptr(std::weak_ptr<Foo>);