Is there any overhead using this-> for accessing a member?

前端 未结 5 1046
死守一世寂寞
死守一世寂寞 2021-01-11 17:33

When accessing a member of some class, I can use e.g.:

this->myVar = 10 

or I can just write:

myVar = 10
相关标签:
5条回答
  • 2021-01-11 18:07

    Those two lines of code have the same meaning. The this-> is implicit in the second line. They do exactly the same thing.

    Thus, they perform exactly the same as well :-)

    0 讨论(0)
  • 2021-01-11 18:09

    I like to use this-> because it explicitly declares that the variable is a member of this class, but does it occur any overhead in comparison to just using the variable name by itself?

    Yes, it's more to write, and more to read, and indicates to readers of the code that it was written by someone not familiar with C++, so that they have to use extra time on carefully checking everything. All of that is programmers' overhead. It costs money.

    There is, however, no overhead of the kind that generally doesn't cost anything, efficiency of generated machine code.

    Summing up, there is overhead of the costly kind, and none of the cheap/free kind.

    As an alternative I could maybe add a unique prefix to the vars, such as _TmyVar, but I've been using this-> for a long time so I just wondered.

    Names of the form _TmyVar, starting with underscore followed by uppercase letter, are reserved for the implementation.

    Don't do that.

    The two most common C++ naming conventions for non-static data members are myVar (prefix my) and var_ (suffix _).

    Cheers & hth.,

    0 讨论(0)
  • 2021-01-11 18:17

    There is no difference in meaning (unless there's more than one name myVar visible, in which case the ordinary version could mean a function-local variable while this->myVar means a member). So yes, it's just a matter of style.

    0 讨论(0)
  • 2021-01-11 18:18

    I sometimes uses explicit this-> in setters, since they allow me to use the same name for the parameter names as the instance fields:

    class MyClass 
    {
        int foo;
        void setFoo(int foo) 
        {
            this->foo = foo;
        }
    }
    

    however, in constructors, I usually use initialization list, which does not require an explicit this->

    class MyClass 
    {
        int foo;
        MyClass(int foo) : 
            foo(foo) 
        { 
        }
    }
    
    0 讨论(0)
  • 2021-01-11 18:20

    There is no overhead. The compiler will generate the exact same code for both versions.

    0 讨论(0)
提交回复
热议问题