Avoid Leading Underscores
Posted on July 25th, 2009 at 17:48 by fr3@K

在很多 code base 裏面都能看到在前面加個 underscore (底線/下滑线) 的 function/macro/variable. 常常是用來暗示某個 name 是 local/private, 有時是用來避免 name collision.

GoF 的經典巨著 Design Patterns 裏面, 以及一個時期的 Herb Sutter (the GURU), 都以在前面加上底線的方式標示 member data.

所有我見過的 Standard Library 的 implementation 不但都以在前面加個 underscore (底線/下滑线) 的方式命名 inclusion guard,1 也多用這方法替 member data 以及非公開的 identifier 起名字. Windows 則更是出了名的有許多在前面加了個 underscore 的標準 (documented) Win32 API.

可是關於 leading underscore, 標準是這麼說的: 2

Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

所有以 underscore 起頭的 identifier 都是保留給 compiler/standard library 實作任意使用的. 也就是說如果使用者自行定義了這樣的 identifier, 結果是無法預期的. 運氣好, 在 compile 時就得到 compiler error. 倒楣的話 undefined behavior 也不是不可能發生.

在實踐上, 這樣的 code 有很大的機會可以在你現在使用的 compiler 之下能正常編譯與運作, 但卻不能保證它就能在另一個 compiler (甚至是同一 compiler 的下一個版本) 之下也會得到相同的結果.3

延伸閱讀: Item 11 of GotW #4.

  1. vector 為例, VC++ 的叫 _VECTOR_. libstdc++ 的是 _GLIBCXX_VECTOR []
  2. C++98 17.4.3.1.2 []
  3. SmallWindows port 到 Unix 時就遇到了這樣的問題 []
del.icio.us:Avoid Leading Underscores digg:Avoid Leading Underscores spurl:Avoid Leading Underscores newsvine:Avoid Leading Underscores furl:Avoid Leading Underscores Y!:Avoid Leading Underscores 黑米共享書籤:Avoid Leading Underscores 推推王:Avoid Leading Underscores
Previous Post
« 日蝕 «
Next Post
» The C++0x “Remove Concepts” Decision »

1 Comment »

Comment #8559

記得 leading underscore 的濫觴是 Scott Meyers 的 Effective C++。

Comment by jeffhung — July 30, 2009 @ 10:39


Comments RSS TrackBack URI

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>