Home

Awesome

observable_unique_ptr, observable_sealed_ptr, observer_ptr

Build Status Docs Build Status codecov

Built and tested on:

Table of content:

<!-- MarkdownTOC autolink="true" --> <!-- /MarkdownTOC -->

Introduction

This is a small header-only library, providing the unique-ownership smart pointers observable_unique_ptr and observable_sealed_ptr that can be observed with non-owning pointers observer_ptr. This is a mixture of std::unique_ptr and std::shared_ptr: it borrows the unique-ownership semantic of std::unique_ptr (movable, non-copiable), but allows creating observer_ptr to monitor the lifetime of the pointed object (like std::weak_ptr for std::shared_ptr).

The only difference between observable_unique_ptr and observable_sealed_ptr is that the former can release ownership, while the latter cannot. Disallowing release of ownership enables allocation optimizations. Therefore, the recommendation is to use observable_sealed_ptr unless release of ownership is required.

These pointers are useful for cases where the shared-ownership of std::shared_ptr is not desirable, e.g., when lifetime must be carefully controlled and not be allowed to extend, yet non-owning/weak/observer references to the object may exist after the object has been deleted.

Note: Because of the unique ownership model, observer pointers cannot extend the lifetime of the pointed object, hence this library provides less safety compared to std::shared_ptr/std::weak_ptr. See the Thread safety section. This is also true of std::unique_ptr, and is a fundamental limitation of unique ownership. If this is an issue, simply use std::shared_ptr/std::weak_ptr.

Usage

This is a header-only library requiring a C++17-compliant compiler. You have multiple ways to set it up:

From there, include the single header <oup/observable_unique_ptr.hpp>, and directly use the smart pointer in your own code:

#include <oup/observable_unique_ptr.hpp>

#include <string>
#include <iostream>
#include <cassert>

int main() {
    // Non-owning pointer that will outlive the object
    oup::observer_ptr<std::string> obs_ptr;

    {
        // Sealed (unique) pointer that owns the object
        auto owner_ptr = oup::make_observable_sealed<std::string>("hello");

        // A sealed pointer cannot be copied but it can be moved
        // auto tmp_copied = owner_ptr; // error!
        // auto tmp_moved = std::move(owner_ptr); // OK

        // Make the observer pointer point to the object
        obs_ptr = owner_ptr;

        // The observer pointer is now valid
        assert(!obs_ptr.expired());

        // It can be used like a regular raw pointer
        assert(obs_ptr != nullptr);
        std::cout << *obs_ptr << std::endl;

        // An observer pointer can be copied and moved
        // auto tmp_copied = obs_ptr; // OK
        // auto tmp_moved = std::move(obs_ptr); // OK
    }

    // The sealed pointer has gone out of scope, the object is deleted,
    // the observer pointer is now null.
    assert(obs_ptr.expired());
    assert(obs_ptr == nullptr);

    return 0;
}

enable_observer_from_this

As with std::shared_ptr/std::weak_ptr, if you need to obtain an observer pointer to an object when you only have this (i.e., from a member function), you can inherit from oup::enable_observer_from_this_unique<T> or oup::enable_observer_from_this_sealed<T> (depending on the type of the owner pointer) to gain access to the observer_from_this() member function. Contrary to std::enable_shared_from_this<T>, this function is noexcept and is able to return a valid observer pointer at all times, even if the object is being constructed or is not owned by a unique or sealed pointer. Also contrary to std::enable_shared_from_this<T>, this feature naturally supports multiple inheritance.

To achieve this, the price to pay is that oup::enable_observer_from_this_unique<T> uses virtual inheritance, while oup::enable_observer_from_this_sealed<T> requires T's constructor to take a control block as input (thereby preventing T from being default-constructible, copiable, or movable). If needed, these trade-offs can be controlled by policies, see below.

Policies

Similarly to std::string and std::basic_string, this library provides both "convenience" types (oup::observable_unique_ptr<T,Deleter>, oup::observable_sealed_ptr<T>, oup::observer_ptr<T>, oup::enable_observable_from_this_unique<T>, oup::enable_observable_from_this_sealed<T>) and "generic" types (oup::basic_observable_ptr<T,Deleter,Policy>, oup::basic_observer_ptr<T,ObsPolicy>, oup::basic_enable_observable_from_this<T,Policy>).

If the trade-offs chosen to defined the "convenience" types are not appropriate for your use cases, they can be fine-tuned using the generic classes and providing your own choice of policies. Please refer to the documentation for more information on policies. In particular, policies will control most of the API and behavior of the enable_observable_from_this feature, as well as allowing you to tune the size of the reference counting object (speed/memory trade-off).

Limitations

The following limitations are features that were not implemented simply because of lack of motivation.

Thread safety

This library uses reference counting to handle observable and observer pointers. The current implementation does not use any synchronization mechanism (mutex, lock, etc.) to wrap operations on the reference counter. Therefore, it is unsafe to have an observable pointer on one thread being observed by observer pointers on another thread.

The above could be fixed in the future by adding a configurable policy to enable or disable synchronization. However, the unique ownership model still imposes fundamental limitations on thread safety: an observer pointer cannot extend the lifetime of the observed object (like std::weak_ptr::lock() would do). The only guarantee that could be offered is the following: if expired() returns true, the observed pointer is guaranteed to remain nullptr forever, with no race condition. If expired() returns false, the pointer could still expire on the next instant, which can lead to race conditions. To completely avoid race conditions, you will need to add explicit synchronization around your object.

Finally, because this library uses no global state (beyond the standard allocator, which is thread-safe), it is perfectly fine to use it in a threaded application, provided that all observer pointers for a given object live on the same thread as the object itself.

Comparison spreadsheet

In this comparison spreadsheet, the raw pointer T* is assumed to never be owning, and used only to observe an existing object (which may or may not have been deleted). Unless otherwise specified, the stack and heap sizes were measured with gcc 9.4.0 and libstdc++-9.

Labels:

Pointerrawweakobserveruniquesharedobs_uniqueobs_sealed
Owningnononoyesyesyesyes
ReleasableN/AN/AN/Ayesnoyesno
Observable deletionnoyesyesyesyesyesyes
Thread-safenoyesnonoyesnono
Atomicyesno(1)nonono(1)nono
Support arraysyesyesnoyesyesnono
Support custom allocatorN/Ayesnoyesyesnono
Support custom deleterN/AN/AN/Ayesyes(2)yesno
Max number of observersinf.?(3)2^31 - 11?(3)11
Number of heap alloc.00011/2(4)21
Size in bytes (64 bit)
- Stack (per instance)816168161616
- Heap (shared)000024(5)44(6)
- Total816168402020
Size in bytes (32 bit)
- Stack (per instance)4884888
- Heap (shared)00001644
- Total4884241212

Notes:

Speed benchmarks

Labels are the same as in the comparison spreadsheet. The speed benchmarks were compiled with all optimizations turned on (except LTO). Speed is measured relative to std::unique_ptr<T> used as owner pointer, and T* used as observer pointer, which should be the fastest possible implementation (but obviously the one with least safety).

You can run the benchmarks yourself, they are located in tests/speed_benchmark.cpp. The benchmark executable runs tests for three object types: int, float, std::string, and std::array<int,65'536>, to simulate objects of various allocation cost. The timings below are the median values measured across all object types, which should be most relevant to highlight the overhead from the pointer itself (and erases flukes from the benchmarking framework). In real life scenarios, the actual measured overhead will be substantially lower, as actual business logic is likely to dominate the time budget.

Detail of the benchmarks:

The benchmarks were last ran for oup v0.7.1.

Compiler: gcc 9.4.0, std: libstdc++-9, OS: linux 5.15.0, CPU: Ryzen 5 2600:

Pointerraw/uniqueweak/sharedobserver/obs_uniqueobserver/obs_sealed
Create owner empty11.11.11.2
Create owner12.11.7N/A
Create owner factory11.31.71.1
Dereference owner11.01.01.1
Create observer empty11.11.21.2
Create observer11.61.61.6
Create observer copy11.71.61.6
Dereference observer13.51.01.0

Compiler: MSVC 16.11.3, std: MS-STL, OS: Windows 10.0.19043, CPU: i7-7800x:

Pointerraw/uniqueweak/sharedobserver/obs_uniqueobserver/obs_sealed
Create owner empty11.41.81.5
Create owner12.22.9N/A
Create owner factory11.22.20.9
Dereference owner10.71.31.0
Create observer empty11.61.00.8
Create observer15.31.61.6
Create observer copy15.31.41.5
Dereference observer19.41.40.8

Compiler: Emscripten 2.0.34, std: libc++, OS: Node.js 14.15.5 + linux kernel 5.1.0, CPU: Ryzen 5 2600:

Pointerraw/uniqueweak/sharedobserver/obs_uniqueobserver/obs_sealed
Create owner empty16.91.11.0
Create owner11.81.6N/A
Create owner factory11.21.71.0
Dereference owner11.01.01.0
Create observer empty111.41.61.6
Create observer114.82.32.3
Create observer copy114.92.32.5
Dereference observer138.71.01.0

Alternative implementation

An alternative implementation of an "observable unique pointer" can be found here. It does not compile out of the box with gcc unfortunately and lacks certain features (their make_observable always performs two allocations). Have a look to check if this better suits your needs.