Subject: Re: [boost] Is there any interest in non-owning pointer-like types?
From: Rob Stewart (rstewart_at_[hidden])
Date: 2017-02-01 04:27:10
On February 1, 2017 2:47:54 AM EST, Joseph Thomson <joseph.thomson_at_[hidden]> wrote:
> For some time, I have been developing a pair of non-owning
> types that I am currently calling `observer_ptr` and `observer`.
> The `observer_ptr<T>` class template is a pointer-like type that does
> do any resource management, and is intended to be used in place of
> wherever `T*` is used as a non-owning reference to an object of type
> `observer_ptr<T>` has three main advantages over `T*`:
> 1. `T&` is implicitly convertible to `observer_ptr<T>` which, unlike
> makes it *type-safe*. `T*` can represent things that are not
> conceptually objects of type `T`: arrays, strings, iterators. No
> implicit conversion from `T*` means that these things cannot
> convert to `observer_ptr<T>`. Pointers aren't even required to point
> valid objects (e.g. a past-the-end iterator). Conversely, in a
> program, `T&` is *always* a valid object of type `T`.
> 2. `observer_ptr<T>` documents its purpose. This is really a
> of it being type-safe (a type should have a single, specific purpose),
> it's worth mentioning. Conversely, when you see `T*`, it may not be
> immediately obvious what it represents.
> 3. `observer_ptr<T>` has a minimal interface, which makes it harder to
> misuse than `T*`; for example, `observer_ptr<T>` has no pointer
> arithmetic operators, no array subscript operator, no conversion to
Can observer_ptr refer to no object? If not, why not just use T &? If so, why not just use optional<T>?
> The `observer<T>` class template is a counterpart to `observer_ptr<T>`
> has *no null state*; it cannot be default constructed, constructed
> `nullptr_t` or constructed from `T*`, and it does not contextually
> to `bool`. The only way to create an `observer<T>` is from `T&`. This
> allows a "not null" precondition to be enforced at compile-time,
> than having to worry about pointers being null at run-time.
How is this better than T &?
-- Rob (Sent from my portable computation device.)