Croolman
Croolman

Reputation: 1123

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

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.

Upvotes: 5

Views: 185

Answers (1)

Passer By
Passer By

Reputation: 21130

You "poison" overload resolution on rvalues

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

Upvotes: 4

Related Questions