Trailing underscores for member variables in C++

2019-01-22 01:40发布

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 variables as members, that's what "m_" is for. It's actual purpose is to make it possible to have an accessor method named like the field, like this:

class Foo {
public:
    bar the_bar() { return the_bar_; }
private:
    bar the_bar_;
}

Having accessors omit the "get_" part is common in the STL and boost, and I'm trying to develop a coding style as close to these as possible, but I can't really see them using the underscore trick. I wasn't able to find an accessor in STL or boost that would just return a private variable.

I have a few questions I'm hoping you will be able to answer:

  1. Where does this convention come from? Smalltalk? Objective-C? Microsoft? I'm wondering.
  2. Would I use the trailing underscore for all private members or just as a workaround in case I want to name a function like a variable?
  3. Can you point me to STL or boost code that demonstrates trailing underscores for member variables?
  4. Does anybody know what Stroustrup's views on the issue are?
  5. Can you point me to further discussion of the issue?

7条回答
我命由我不由天
2楼-- · 2019-01-22 02:19

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)

查看更多
登录 后发表回答