澄清智能指针的运算符*和运算符 - >重载

use*_*193 4 c++ pointers smart-pointers operator-overloading

因为我使用了c ++所以它通过了很多,所以这里(可能是愚蠢的)问题:

一个基本的智能指针Object应该像普通的指针一样,所以在典型的实现中我们将*->运算符添加到对象中,如下所示:

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;}
   // ...
};
Run Code Online (Sandbox Code Playgroud)

现在,在我的知识中,c ++ *运算符(dereference)代表:"通过ptr的值获取堆中指向的值"(是不是?),*ptr应该是类型T.那么为什么我们会返回一个地址呢?

T& operator*()              {return *ptr;}
Run Code Online (Sandbox Code Playgroud)

代替:

T operator*()              {return *ptr;}
Run Code Online (Sandbox Code Playgroud)

其次,通过以下代码段:

void foo()
{
    auto_ptr<MyClass> p(new MyClass);
    p->DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

现在,我怎么才能ptr->DoSomething()通过写作来访问方法p->DoSomething()?从逻辑上讲,我会写错了代码:

p->->DoSomething();
Run Code Online (Sandbox Code Playgroud)

因为p->返回a T*然后我需要另一个->运算符来访问该DoSomething()方法.

感谢您的回答/澄清,并抱歉最终糟糕的英语.

Ker*_* SB 5

在C++中,当您评估函数时,最终得到一个值(除非函数的返回类型是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"
Run Code Online (Sandbox Code Playgroud)

因此,如果您希望函数生成您不想复制的现有值,则必须将函数的返回类型声明为引用类型之一.如果返回类型不是引用类型,则将生成返回值的副本,并且调用者只能看到该副本.