What is the meaning of "The World Dumbest Smart Pointer"?

The N4282 clause protects a new type of non-owning smart pointer called observer_ptr . His working name was exempt_ptr , and it was intended to replace "raw pointers." But I do not understand its purpose, especially with this hypothetical code, for which it is intended to achieve:

 struct do_nothing { template <class T> void operator ()(T*) { }; // do nothing }; template <class T> using non_owning_ptr = unique_ptr<T, do_nothing>; 

Even after reading the article, I don’t understand the purpose of a smart pointer that does nothing. What advantage does it have over non- shared_ptr or raw pointer?

+6
source share
1 answer

Have you read the Motivation section of proposal N4282 that you contacted?

Often, it often took a programmer a lot of time and time to check the code to distinguish between the use that any particular null pointer is bound to, even if that use has no control role at all. As Loyk A. Joli noted, β€œit’s not easy to eliminate the foggy T * pointer that only observes the data ... Even if it just serves for documentation, I will have a certain sense of having a distinguished type.” Our experience allows us to agree with this assessment.

In other words, this makes the code more self-documenting.

For example, if I see the following function:

 void do_something(Foo *foo); 

then I don’t know if do_something accepts ownership of foo, whether Foo wants an array of indefinite length, just needs a reference to NULL, uses it as a Google C ++ Style Guide , or outdated C style code that just wants a link.

However, if I see

 void do_something(observer_ptr<Foo> foo); 

then I know that he is watching an instance of Foo and no more.

The basic C ++ recommendations contain several additional examples ( owner , not_null , etc.) of using templates, not to add functionality at runtime, but to better document the behavior.

+8
source

All Articles