C++ Logo

STD-PROPOSALS

Advanced search

Subject: [std-proposals] Adding a nullptr_t constructor to weak_ptr
From: Ben Hetherington (dev_at_[hidden])
Date: 2019-11-24 06:35:33


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!

-Ben


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

Standard Proposals Archives on Google Groups