Tag Archive: singleton


Global Variables in C and C++

先簡單的介紹一下 C 與 C++ 處理 global variable initialization 的差異. 下面的 code snip 定義了四個 non-auto variable, 它們的 life scope 都 (可以) 是全局的, 要到程式 termination 才結束. 因此它們都可算是 實質上的 global variable, 本文也將以 global variable 稱之:

    int global_1 = 1;
    
    int* foo()
    {
      static int global_2 = 1;
      return &global_2;
    }
    
    int global_3 = *foo();
    
    int* bar()
    {
      static int global_4 = *foo();
      return &global_4;
    }
    

以 GCC 為例, 這段 code 可以合法地當作 C++ source code 編譯:

    freak@blizzard:~/tmp$ # when compiled as C++, it went just fine.
    freak@blizzard:~/tmp$
    freak@blizzard:~/tmp$ gcc -x c++ -c globals.c
    freak@blizzard:~/tmp$ 

卻會被 C compiler 拒絕:

    freak@blizzard:~/tmp$ # when compiled as good old C, compiler complains.
    freak@blizzard:~/tmp$
    freak@blizzard:~/tmp$ gcc -x c -c globals.c
    globals.c:9: error: initializer element is not constant
    globals.c: In function ‘bar’:
    globals.c:13: error: initializer element is not constant
    freak@blizzard:~/tmp$ 

View full article »

幾乎所有 programmer 都知道 evil global variables 這句話. Global variable 的最大問題之一是 scope. 通常一個 variable 的 scope 愈大, 能帶來的 complexity 就愈大.

但現實是, 在任何有意義的程式中, 我們幾乎總是無法避免 global variable. 即便是 C/C++ 的 Standard Library 都提供了 global variable 給 client code 使用, 如 errno, stdin/stdout.
View full article »

去年我寫過一篇文章, 大意是在說 大多數人所使用的 Singleton 實作都是有問題的. 在文章靠近後面的部份, 我也介紹了一種較少為人知, 我常用在 lifetime 是全局但 scope 是局部的 (global) 變數的 Singleton 實作. 雖然這實作離 fool proof 還差得遠, 在使用者能夠正確地 include header 的情況下, 它可能已經是最接近 bullet proof 的實作了.

“好吧, 那我就用類似你的 Singleton 實作總行了吧!?” 先別急著動手改 code, 實作是容易更換的, 但使用 Singleton Pattern 的原因卻與更重要的介面, 甚至架構的設計思維息息相關. 工作的實務經驗以及本身的興趣研究讓我體會到, 大多數的情況下 Singleton 的使用是可以避免的. 在這些非必要情況卻依然採用 Singleton 的原因常是:

  • 沒把問題想清楚
  • 好玩
  • 因為有個叫作 Singleton 的 pattern

View full article »

Singleton 是 C++ 程式設計裡,最古老的問題之一。典型的 (狹義的) singleton 是用一個 class 的 static member function 封裝,稱為 singleton pattern。The Gang of Four (GoF) 在 Design Patterns 討論並提出第一個 (在某種程度上似乎) 令人滿意的 singleton 解答,這個 pattern 幾乎是一夕之間聲名大噪,成為 (可能是) 最廣為人知的 pattern。不論在 GoF 之前與之後,許多人 (其中不乏大師級人物) 提出了不同的 singleton pattern,要解決的問題主要是:

  • 確保某單一 instance 的存在
  • 提供單一介面 (接口) 以存取該 instance
  • 確保該 instance 能被正確建構與解構 (虛構)
  • 確保該 instance 的有正確的生存週期

這裡的討論會把範圍放大,不只 singleton pattern,還要含括廣義的 singleton,也就是 - global 變數 (以下除非特別註明,singleton 指的是廣義的 singleton)。
View full article »