Why use prefixes on member variables in C++ classes

前端 未结 29 1399
半阙折子戏
半阙折子戏 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:46

    The original idea for prefixes on C++ member variables was to store additional type information that the compiler didn't know about. So for example, you could have a string that's a fixed length of chars, and another that's variable and terminated by a '\0'. To the compiler they're both char *, but if you try to copy from one to the other you get in huge trouble. So, off the top of my head,

    char *aszFred = "Hi I'm a null-terminated string";
    char *arrWilma = {'O', 'o', 'p', 's'};

    where "asz" means this variable is "ascii string (zero-terminated) and "arr" means this variable is a character array.

    Then the magic happens. The compiler will be perfectly happy with this statement:

    strcpy(arrWilma, aszFred);

    But you, as a human, can look at it and say "hey, those variables aren't really the same type, I can't do that".

    Unfortunately a lot places use standards such as "m_" for member variables, "i" for integers no matter how used, "cp" for char pointers. In other words they're duplicating what the compiler knows, and making the code hard to read at the same time. I believe this pernicious practice should be outlawed by statute and subject to harsh penalties.

    Finally, there's two points I should mention:

    • Judicious use of C++ features allows the compiler to know the information you had to encode in raw C-style variables. You can make classes that will only allow valid operations. This should be done as much as practical.
    • If your code blocks are so long that you forget what type a variable is before you use it, they are way too long. Don't use names, re-organize.

提交回复
热议问题