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

前端 未结 5 1088
死守一世寂寞
死守一世寂寞 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: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.,

提交回复
热议问题