轉錄至https://coherence0815.wordpress.com/2014/08/13/unnamed-namespace-in-cpp/
根據C++的standard:
The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.
在C語言中,我們為了避免translation unit之間不必要的耦合,我們常會使用static關鍵字來修飾global variable或global function,用以限制該global variable或global function的能見度只在該translation unit之中。而在C++中,unnamed namespace就是用來當作static關鍵字的一個替代方案,原因如下:
1. static關鍵字不能用來修飾user-defined type,也就是class和struct:
1
2
3
4
5
6
|
static class Cls{ public : Cls(){ m_nData = 0; } private : int m_nData; }; |
用MSVC 2008編譯以上這段程式,會出現warning,compiler會忽略static關鍵字:
warning C4091: ‘static ‘ : ignored on left of ‘Cls’ when no variable is declared
若使用unnamed namespace就是合法的,不會有warning:
1
2
3
4
5
6
7
8
9
10
11
|
namespace { class Cls { public : Cls(){} private : int m_nData; }; } |
2. static修飾的東西不同,意思也不盡相同,常對初學者帶來混淆;而namespace提供了統一的方式,用來解決在global scope下symbol能見度的一些問題(因為namesapce本來就是為了處理naming的問題而存在)。若要限制global variable或global function的能見度只在該translation unit中,使用unnamed namespace是比較恰當的作法。