Search code examples
c++operator-overloadingsmart-pointersdereference

Regarding definition of dereferencing and member selection operators in smart pointer


In smart pointer implementation, dereferencing operator and member selection operators are always defined as below.

T& operator* () const     // dereferencing operator
{
    return *(m_pRawPointer); 
}

T* operator->() const     // member selection operator
{
    return m_pRowPointer;
}

I don't quite understand why the former is returned by reference, the latter is returned by pointer. Is it just to differentiate them or some other reasons? To be more specific, can I make dereferencing operator returns by pointer, while the other one returns by reference?


Solution

  • why the former is returned by reference

    So that the expression *thing gives an lvalue denoting an object of type T, just as it would if thing were a pointer.

    the latter is returned by pointer

    Because that's how the language is specified. Note that you never use the result of -> directly, but always in an expression of the form thing->member.

    If thing is a class type, that's evaluated by calling operator->, then applying ->member to the result of that. To support that, it must return either a pointer, or another class type which also overloads operator->.

    can I make dereferencing operator returns by pointer

    Yes, but that would be rather confusing since it would behave differently to applying the same operator a pointer. You'd have to say **thing to access the T.

    while the other one returns by reference

    No, because that would break the language's built-in assumptions about how the overloaded operator should work, making it unusable.