Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
136 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...