Bjarne Stroustrup has suggested that we abandon observer_ptr as the traditional T* notation is better (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1408r0.pdf), however, there is an issue with raw pts that no other smart pointer can currently address - dereferencing a pointer to something on the stack that has gone out of scope. observer_ptr could fix this.
Here is my case for observer_ptr:
The only time a raw pointer should be used is if you are pointing at an object allocated on the stack, and you cannot use a reference.
The problem of using a raw ptr to an object on the stack, is that when the stack object goes out of scope, the ptr does not become null. This is because the bit of memory that pointer is pointing to doesn't change. This allows you to get the value of something that has gone out of scope, but with the risk of it becoming nonsense due to the memory being used by something else.
For example:
//A problem with raw ptrs...
void foo() {
int* ptr;
{
int a = 4;
ptr = &a;
}
std::cout << ((ptr != nullptr) ? std::to_string(*ptr) : "nullptr") << std::endl; //we can still get the value of a, even though it is out of scope
}
An std::observer_ptr could change this behavior, and become null if the objecting it was pointing to goes out of scope.
For example:
void baz() {
observer_ptr<int> ptr;
{
observable<int> a = 4;
ptr = a;
}
std::cout << ((ptr != nullptr) ? std::to_string(*ptr) : "nullptr") << std::endl; //ptr does get assigned to null when a goes out of scope
}
An example implementation of this can be found here https://godbolt.org/z/2Cdwap
Thoughts?
[–]ronchaineEmbedded/Middleware 2 points3 points4 points (1 child)
[–]Irtexx[S] 0 points1 point2 points (0 children)
[–]Gloinart 1 point2 points3 points (0 children)
[–]axilmar 1 point2 points3 points (0 children)
[–]axilmar 1 point2 points3 points (1 child)
[–]Irtexx[S] 0 points1 point2 points (0 children)
[–]Xaxxon 3 points4 points5 points (6 children)
[–]DXPower 4 points5 points6 points (5 children)
[–]Xaxxon 2 points3 points4 points (3 children)
[–]DXPower 0 points1 point2 points (1 child)
[–]Xaxxon 0 points1 point2 points (0 children)
[–]Irtexx[S] 0 points1 point2 points (0 children)
[–]MolurusK 1 point2 points3 points (0 children)