Why use prefixes on member variables in C++ classes

前端 未结 29 1404
半阙折子戏
半阙折子戏 2020-11-28 17:39

A lot of C++ code uses syntactical conventions for marking up member variables. Common examples include

  • m_memberName for public members (where public
29条回答
  •  伪装坚强ぢ
    2020-11-28 17:43

    I generally don't use a prefix for member variables.

    I used to use a m prefix, until someone pointed out that "C++ already has a standard prefix for member access: this->.

    So that's what I use now. That is, when there is ambiguity, I add the this-> prefix, but usually, no ambiguity exists, and I can just refer directly to the variable name.

    To me, that's the best of both worlds. I have a prefix I can use when I need it, and I'm free to leave it out whenever possible.

    Of course, the obvious counter to this is "yes, but then you can't see at a glance whether a variable is a class member or not".

    To which I say "so what? If you need to know that, your class probably has too much state. Or the function is too big and complicated".

    In practice, I've found that this works extremely well. As an added bonus it allows me to promote a local variable to a class member (or the other way around) easily, without having to rename it.

    And best of all, it is consistent! I don't have to do anything special or remember any conventions to maintain consistency.


    By the way, you shouldn't use leading underscores for your class members. You get uncomfortably close to names that are reserved by the implementation.

    The standard reserves all names starting with double underscore or underscore followed by capital letter. It also reserves all names starting with a single underscore in the global namespace.

    So a class member with a leading underscore followed by a lower-case letter is legal, but sooner or late you're going to do the same to an identifier starting with upper-case, or otherwise break one of the above rules.

    So it's easier to just avoid leading underscores. Use a postfix underscore, or a m_ or just m prefix if you want to encode scope in the variable name.

提交回复
热议问题