c++c++20type-traitsc++-conceptsweak-ptr

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.


Solution

  • You "poison" overload resolution on rvalues

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