Clarification when working with the smart pointer * operator and operator->

it went a lot since I used C ++, so here's the (probably dumb) question:

The main smart pointer The object should behave like a regular pointer, so in a typical implementation we add an operator to the object *and ->, something like this:

template <class T> class auto_ptr
{
    T* ptr;
    public:
    explicit auto_ptr(T* p = 0) : ptr(p) {}
    ~auto_ptr()                 {delete ptr;}
    T& operator*()              {return *ptr;}
    T* operator->()             {return ptr;}
   // ...
};

Now, in my opinion, the C ++ *(dereferencing) operator means: "get the value indicated on the heap by the ptr value" (right?), And the type *ptrshould be T. So why do we get the address back?

T& operator*()              {return *ptr;}

Instead:

T operator*()              {return *ptr;}

Secondly, having the following snippet:

void foo()
{
    auto_ptr<MyClass> p(new MyClass);
    p->DoSomething();
}

Now, how can I access the method ptr->DoSomething()by simply writing p->DoSomething()? Logically, I would write the wrong code:

p->->DoSomething();

p-> T*, -> DoSomething().

/ .

+4
3

++, , ( void). . , f(), T. :

T    f();    =>   f() is a prvalue, passed along by copy
T &  f();    =>   f() is an lvalue, the same object that is bound to "return"
T && f();    =>   f() is an xvalue, the same object that is bound to "return"

, , , , . , , - .

+5

, p->->DoSomething, , operator-> , , , T*.

p-> T*, , MyClass, operator..

, .

+2

, , ,

*somePointer = someValue;

and the meaning of what indicates somePointerwould change to someValue. If you return by value, the above expression will have a temporary value to which it is assigned, and then this temporary value will be destroyed and the change will be lost.

+1
source

Source: https://habr.com/ru/post/1534805/


All Articles