Home > Back-end >  How to ensure a weak_ptr is not created from a temporary shared_ptr?
How to ensure a weak_ptr is not created from a temporary shared_ptr?

Time:07-11

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.

CodePudding user response:

You "poison" overload resolution on rvalues

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