/* 有時候可能會用到static變量,如果將static變量定義成non-local的,
那麼我們無法保障在需要使用該變量的時候該變量已經進行被初始化了;
解決該問題的方式是將non-local的靜態變量定義到函數內,
然後通過返回該靜態變量的引用的形式使調用者獲取到靜態變量;
該靜態變量在函數被第一次調用的時候被初始化 */
#include <iostream>
class Supplier;
class Printer;
Supplier &getSupplier();
Printer &getPrinter();
class Supplier
{
public:
Supplier(int id = 0) : m_id(id) {
std::cout << "Book ctor called." << std::endl;
}
~Supplier() {}
int getId() {
return m_id;
}
private:
int m_id;
};
class Printer
{
public:
Printer(int id = 0)/* : m_supplier_id(getSupplier().getId())*/ {
m_supplier_id = getSupplier().getId();
std::cout << "Printer ctor called." << std::endl;
}
~Printer() {}
private:
int m_supplier_id;
};
/* 以函數調用返回一個reference指向local static對象,替換直接訪問non-local static對象 */
Supplier &getSupplier()
{
static Supplier stabook; /* 第一次調用該函數時stabook被初始化,會去執行Supplier的構造函數,
再次調用時這句不會再去執行Supplier的構造函數 */
return stabook;
}
/* 以函數調用返回一個reference指向local static對象,替換直接訪問non-local static對象 */
Printer &getPrinter()
{
static Printer staprinter;
return staprinter;
}
int main() {
Supplier aSupplier;
Printer aPrinter;
Printer bPrinter;
return 0;
}
Reference
Scott Meyers. Effective C++ , 55 Specific Ways to Improve Your Programs and Designs, Third Edition