Boost logo

Boost :

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
> pointer-like
> types that I am currently calling `observer_ptr` and `observer`.


> The `observer_ptr<T>` class template is a pointer-like type that does
> not
> do any resource management, and is intended to be used in place of
> `T*`
> wherever `T*` is used as a non-owning reference to an object of type
> `T`.
> `observer_ptr<T>` has three main advantages over `T*`:
> 1. `T&` is implicitly convertible to `observer_ptr<T>` which, unlike
> `T*`,
> 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
> implicitly
> convert to `observer_ptr<T>`. Pointers aren't even required to point
> to
> valid objects (e.g. a past-the-end iterator). Conversely, in a
> well-formed
> program, `T&` is *always* a valid object of type `T`.
> 2. `observer_ptr<T>` documents its purpose. This is really a
> side-effect
> of it being type-safe (a type should have a single, specific purpose),
> but
> 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
> `void*`.

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>`
> that
> has *no null state*; it cannot be default constructed, constructed
> from
> `nullptr_t` or constructed from `T*`, and it does not contextually
> convert
> 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,
> rather
> than having to worry about pointers being null at run-time.

How is this better than T &?

(Sent from my portable computation device.)

Boost list run by bdawes at, gregod at, cpdaniel at, john at