2

I have a simple smart pointer implementation shown in code snippet 1 below. And a dummy test class named Dummy in the 2nd snippet. The code snippet 3 shows how we can utilize this simple smart pointer to access the function foo().

My question is about the way we invoke the function foo() in class Dummy by using the -> operator. -> operator already returns a pointer to the raw pointer. So, I think, in order for us to be able to invoke function foo(), we need to perform a second -> operation on the returned raw pointer. However, many resources say that a single use of the -> operator is sufficient simply.

Briefly, I think that correct call should be like the following: (dummy->)->foo();

However, the call like this dummy->foo() works fine. Can someone explain me why (dummy->)->foo() is incorrect? Perhaps, I have a conceptual misunderstanding but I would like to know the concept right.

CODE SNIPPET 1 (SMART POINTER Class)

template <typename T>
class SmartPointer
{
 private:
    T* mRawPointer;

 public:
    SmartPointer(T* thePointer) : mRawPointer(thePointer) {}
    ~SmartPointer() { delete mRawPointer;}

    T& operator* () const { return *mRawPointer; }

    T* operator-> () const { return mRawPointer; }

};

CODE SNIPPET 2 (Class Dummy)

class Dummy
{
 public:
   foo() {......}
};

CODE SNIPPET 3 (INVOCATTION ALTERNATIVES IN QUESTION)

SmartPointer<Dummy> dummy(new Dummy());

(dummy->)->func(); 
//I think the above is correct cause we need to make a second dereference on the 
//returned raw pointer
//OR
dummy->func();
4

2 回答 2

3

就是这样,因为标准是这样说的......

如果 T::operator->() 存在并且运算符被选为最佳匹配函数,则表达式 x->m 被解释为 (x.operator->())->m 用于类型 T 的类对象 x通过重载解决机制

于 2013-11-14T20:21:30.653 回答
1

这样想:

dummy->实际上返回Dummy*。该标准允许在重载 operator->() 时,单个箭头足以推断 1) 重载的运算符和 2) 底层原始指针。

如果没有这种机制,我们就不能真正拥有“智能”指针,因为它和原始指针之间的语法会有所不同。

于 2013-11-14T20:26:09.083 回答