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();
有帮助吗?

解决方案

It's the way it is because the standard says so...

An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism

其他提示

Think of it this way:

dummy-> in effect returns Dummy*. The standard permits that when overloading operator->(), a single arrow is sufficient to deduce 1) the overloaded operator and 2) the underlying raw pointer.

Without this mechanism we could not truly have "smart" pointers as the syntax between that and a raw pointer would be different.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top