首頁 / CompScience / Programming / Languages / C_and_CPP / Avoid Using Directives

Avoid Using Directives

C++ Primer 4/e在Namespaces這個地方有一個警告:『using directives, which inject all the names from a namespace, are deceptively simple to use: With only a single statement, all the member names of a namespace are suddenly visible. Although this approach may seem simple, it can introduce its own problems. If an application uses many libraries, and if the names within these libraries are made visible with using directives, then we are back to square one, and the global namespace pollution problem reappears.

Moreover, it is possible that a working program will fail to compile when a new version of the library is introduced. This problem can arise if a new version introduces a name that conflicts with a name that the application is using.

Another problem is that ambiguity errors caused by using directives are detected only at the point of use. This late detection means that conflicts can arise long after introducing a particular library. If the program begins using a new part of the library, previously undetected collisions may arise.

Rather than relying on a using directive, it is better to use a using declaration for each namespace name used in the program. Doing so reduces the number of names injected into the namespace. Ambiguity errors caused by using declarations are detected at the point of declaration, not use, and so are easier to find and fix.』

中文版的這樣寫:『using指令會將某個namespace內的所有名稱注射進來。無可否認這樣用很方便:只需一條述句,namespace內的所有成員名稱突然全部曝光。儘管這看起來很簡單,卻會引入一些問題。如果一個程式用了很多程式庫,並以using指令來曝光這些程式庫內的名稱,那麼我們又回到了原點:global命名空間的污染問題再次出現。

此外,導入一個新版程式庫有可能使得原本正確的程式編譯失敗。是的,如果新版程式庫導入一個程式已在使用的名稱,問題就會發生。

另一個問題是,由using指令產生的歧義錯誤只能在使用時才被偵測到。這種後期偵測意味有可能在導入某個程式庫後很長時間才出現衝突。如果程式開始使用這個新版程式庫的某一新成分,上面所說的「未偵測到的衝突」就可能終於爆發。

與其倚賴using指令,不如對程式中用到的每個名稱都使用using宣告式。這能夠減少[注射進入當前namespace」的名稱數。using宣告是導致的歧義錯誤會在宣告點而不是使用點上被偵測到,所以更加容易找到並修補。』

這個濫用using的困擾,卻是心中的痛。

Print Friendly, PDF & Email
馬上成為工作達人的Fans

About ㄚ琪

工作達人Fun Taiwan的創辦者及總編,可以在這裡更認識他。

發表迴響

你的電子郵件位址並不會被公開。 Required fields are marked *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

Scroll To Top