C++ Logo


Advanced search

Re: Adding a nullptr_t constructor to weak_ptr

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Sun, 24 Nov 2019 16:56:40 +0200
On Sun, 24 Nov 2019 at 14:35, 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: 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.
> As things are, this seems like quite an unusual omission, seeing as std::shared_ptr and std::weak_ptr share the same concept of emptiness. If there’s a justification for this omission that I haven’t found, I’d be interested to hear it (I tried searching online and in the mailing list/Google Group history to find any discussion about this, but couldn’t find anything obvious).
> This constructor overload would also allow nullptr to be assigned to existing weak_ptrs, behaving much like the existing reset() method (which is, again, already possible with std::shared_ptr).
> Also, this is my first time making a suggestion for any language's standard library, so do let me know if I suggest or do anything silly here!

I wonder what the value of symmetry with raw pointers is, and how much
way this would really pave for converting
shared_ptrs to weak_ptrs. weak_ptr, despite its name, is not a pointer
and doesn't behave like a pointer, so in that
sense the value of the added symmetry seems potentially negative.

Received on 2019-11-24 08:59:13