Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and when to properly use *this pointer and argument matching?

When I go thru the code written by collegue, in certain place, they use:

this->doSomething(); //-->case A
doSomething(); //-->case B

In fact I'm not sure about the great usage of *this pointer...:(

Another question with argument matching:

obj.doOperation();  //-->case C
(&obj)->doOperation(); //-->case D

In fact both cases are performing the desired operation, is it simply a way to make the code look more complex?

What is your recommendation on the above two question? When is the appropriate time to use them and why?

like image 570
wengseng Avatar asked Jan 22 '23 08:01

wengseng


1 Answers

This is not an answer to your question, but a note that both fragments may do different things:

namespace B { void doSomething() {} }

struct A {    
    void f()
    {
        using B::doSomething;
        this->doSomething(); // call A::doSomething
        doSomething(); // calls B::doSomething
    }

    int a;
    void g(int a)
    {
        this->a = a; // assigns argument to member
    }

    A* operator & () { return this; }
    void doOperation() {}
    void doSomething() {}
};

void g(A &obj)
{
    obj.doOperation();  // calls A::doOperation directly
    (&obj)->doOperation(); // calls A::operator & first
}
like image 136
Yakov Galka Avatar answered Feb 16 '23 03:02

Yakov Galka