C++ Logo

STD-PROPOSALS

Advanced search

Subject: Re: [std-proposals] Adding a nullptr_t constructor to weak_ptr
From: Arthur O'Dwyer (arthur.j.odwyer_at_[hidden])
Date: 2019-11-24 12:10:56


On Sun, Nov 24, 2019 at 7:35 AM Ben Hetherington via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> It'd be great to see a constructor that allows you to construct an empty
> std::weak_ptr using a nullptr literal, such as:
>
> constexpr weak_ptr( std::nullptr_t ) noexcept;
>
> Much like the nullptr_t constructor for std::shared_ptr, this would
> construct an empty std::weak_ptr, just like the default constructor.
>
> While it is already possible to use the default constructor (either
> written out explicitly or expressed as {}) in these situations, I think
> this would be a nice small addition

A weak_ptr is not itself any kind of pointer; you can't dereference a
weak_ptr. Think of a weak_ptr as a "ticket for a shared_ptr." (I strongly
recommend watching my CppCon 2019 talk "Back to Basics: Smart Pointers"
<https://www.youtube.com/watch?v=xGDLkt-jBJ4>.) Since a weak_ptr isn't a
pointer, it has no natural "null pointer" state. It does have an "expired"
state (and, orthogonally, the controlled pointer might be null or non-null).

There is no reason for "nullptr" to construct an expired std::weak_ptr, any
more than "nullptr" should construct an empty std::optional.

> : as well as providing symmetry with raw pointers, it makes it easier to
> convert code that uses std::shared_ptr (and constructs empty shared_ptrs
> using nullptr) to use std::weak_ptr instead (e.g. if a reference cycle is
> discovered), without causing unnecessary code churn.
>

Have you ever found a case in real code where "change std::shared_ptr to
std::weak_ptr" was an appropriate way to fix a reference cycle? As I say in
the Q&A on my talk, I've never seen that happen in real life, to the point
where I don't even use "reference cycle" as an example in the talk.

Re increasing symmetry between weak_ptr and shared_ptr, by the way, I still
strongly believe in the value of
N4537 "Adding Symmetry Between shared_ptr and weak_ptr"
<http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4537.html>,
a.k.a. `std::shared_ptr::unlock()`. That paper gives a couple of motivating
examples from real-world code for `shared_ptr::unlock()`. However, back in
2015, LEWG was not impressed by this motivation.

HTH,
-Arthur



STD-PROPOSALS list run by herb.sutter at gmail.com

Standard Proposals Archives on Google Groups