Search code examples
c++smart-pointersc++17

Use of observer_ptr


What exactly is the point of the construct std::observer_ptr in the library fundamentals technical specification V2?

It seems to me that all it does is wrap a bare T*, which seems like a superfluous step if it adds no dynamic memory safety.

In all of my code I use std::unique_ptr where I need to take explicit ownership of an object and std::shared_ptr where I can share ownership of an object.

This works very well and prevents accidental dereferencing of an already destroyed object.

std::observer_ptr makes no guarantee about the lifetime of the object observed, of course.

If it were to be constructed from a std::unique_ptr or std::shared_ptr I would see a use in such a structure, but any code that is simply using T* is probably just going to keep doing so and if they plan on moving to anything it would be std::shared_ptr and/or std::unique_ptr (depending on use).


Given a simple example function:

template<typename T>
auto func(std::observer_ptr<T> ptr){}

Where it would be useful if it stopped smart pointers from destroying their stored object while they are being observed.

But if I want to observe a std::shared_ptr or std::unique_ptr I have to write:

auto main() -> int{
    auto uptr = std::make_unique<int>(5);
    auto sptr = std::make_shared<int>(6);
    func(uptr.get());
    func(sptr.get());
}

Which makes it no safer than:

template<typename T>
auto func(T *ptr){}

So, what is the use of this new structure?

Is it just for self-documenting source?


Solution

  • The proposal makes it pretty clear that it's just for self-documentation:

    This paper proposes observer_ptr, a (not very) smart pointer type that takes no ownership responsibility for its pointees, i.e., for the objects it observes. As such, it is intended as a near drop-in replacement for raw pointer types, with the advantage that, as a vocabulary type, it indicates its intended use without need for detailed analysis by code readers.