A weak_ptr
has a very specific purpose: to break shared_ptr
cycles. As an example, std::enable_shared_from_this
is based on letting an object contain a weak_ptr
to itself. If it directly contained a shared_ptr
then that would create a cycle, so instead it has a weak_ptr
.
You use a weak_ptr
where you would otherwise have had a shared_ptr
. The weak_ptr
has a higher cost because in addition to the costs of shared_ptr
there is the object existence checking that produces a shared_ptr
, or not. Also it's a more complex beast so that it's easier to use incorrectly.
I can't think of any way that weak_ptr
has anything to do with “temporary ownership” (except that after checking of existence and using a produced shared_ptr
, that's one temporary shared ownership, which is repeated again and again for each use). For example, std::enable_shared_from_this
has nothing to do with temporary ownership. Ordinarily I would just ignore a source of such a claim, and advice others to ignore it, but cppreference.com is about the best we have in the way of a free online C++ reference. It's odd that it contains a nonsense statement. But, nothing's prefect, as I once remarked to Bjarne in clc++, whereupon he corrected my speling of “prefect”. Hm! Well.
I don't know of any advantage in using a raw pointer rather than a weak_ptr
, where a weak_ptr
is what's required. A raw pointer can't do a weak_ptr
's job of holding on to a shared_ptr
's control block, so it seems to me that the mere idea of replacing a weak_ptr
with a raw pointer is nonsense. But then, the day one stops being surprised by learning things one could never have thought of, is the day one is dead, and so it may be the case that there is some obscure-to-me such use.
Also, there is no advantage in using a weak_ptr
where a raw pointer is what's required. Rather, the weak_ptr
introduces a relatively speaking enormous cost, of control block allocation and reference counting. So I can't think of any situation where it would make sense to replace raw pointers with weak_ptr
, and I don't expect this to be a case where I learn otherwise.