Home > Net >  How to not allow conversion from temporary shared_ptr to weak_ptr for derived types
How to not allow conversion from temporary shared_ptr to weak_ptr for derived types

Time:07-11

I have asked this question for concrete types. The provided solution is sufficient for those, but when it comes to inheritance, it fails. Would there be a solution to that as well?

Lets have a inheritance of classes Foo and IFoo such that class Foo: public IFoo and a function void use_weak_ptr(std::weak_ptr<IFoo>).

Is it possible to ensure that this compiles:

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

And this does not:

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

Godbolt

CodePudding user response:

One of the possible solutions - overload use_weak_ptr for all std::shared_ptr.

template <typename T>
void use_weak_ptr(std::shared_ptr<T>&&) = delete;

https://godbolt.org/z/Tj1a134bd

The linked answer is not a good answer. const std::shared_ptr<IFoo>&& - const is redundant.

  • Related