Trailing underscores for member variables in C++

前端 未结 7 410
后悔当初
后悔当初 2020-12-13 03:46

I\'ve seen people use a trailing underscore for member variables in classes, for instance in the renowned C++ FAQ Lite.

I think that it\'s purpose is not to mark var

相关标签:
7条回答
  • 2020-12-13 04:19

    I am personally a big fan of this guideline: http://geosoft.no/development/cppstyle.html

    It includes omitting the m_ prefix, using an underscore suffix to indicate private member variables and dropping the horrid, annoying-to-type habit of using underscores instead of space, and other, more detailed and specific suggestions, such as naming bools appropriately(isDone instead of just done) and using getVariable() instead of just variable() to name a few.

    0 讨论(0)
  • 2020-12-13 04:22

    I've read The C++ Programming Language and Stroustrup doesn't use any kind of convention for naming members. He never needs to; there is not a single simple accessor/mutator, he has a way of creating very fine object-oriented designs so there's no need to have a method of the same name. He uses structs with public members whenever he needs simple data structures. His methods always seem to be operations. I've also read somewhere that he disencourages the use of names that differ only by one character.

    0 讨论(0)
  • 2020-12-13 04:22

    I'm guessing that utopia would have been to use a leading underscore - this is quite common in Java and C# for members.

    However, for C, leading underscores aren't a good idea, so hence I guess the recommendation by the C++ FAQ Lite to go trailing underscore:

    All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.

    All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.


    (ISO C99 specification, section 7.1.3)

    0 讨论(0)
  • 2020-12-13 04:26

    As a maintenance developer that likes searchability I'm leaning towards m_ as its more searchable. When you, as me, are maintaining big projects with large classes (don't ask) you sometimes wonder: "Hmmm, who mutates state?". A quick search for m_ can give a hint.

    I've also been known to use l_ to indicate local variables but the current project doesn't use that so I'm "clean" these days.

    I'm no fan of hungarian notation. C++ has a strong type system, I use that instead.

    0 讨论(0)
  • 2020-12-13 04:30

    Only speaking for myself... I always use trailing underscore for private data members, regardless if they have accessor functions or not. I don't use m_ mainly because it gets in the way when I mentally spell the variable's name.

    0 讨论(0)
  • 2020-12-13 04:32

    As far as I remember, it's not Microsoft that pushed the trailing underscore code style for members.

    I have read that Stroustrup is pro the trailing underscore.

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