C++單例類(lèi)怎樣實(shí)現(xiàn)懶加載

c++
小樊
84
2024-07-25 17:18:14

在C++中實(shí)現(xiàn)懶加載的單例類(lèi)可以使用靜態(tài)成員變量和靜態(tài)成員函數(shù)來(lái)實(shí)現(xiàn)。以下是一個(gè)示例代碼:

class Singleton {
private:
    static Singleton* instance; // 靜態(tài)成員變量

    Singleton() { } // 防止外部實(shí)例化
public:
    static Singleton* getInstance() { // 靜態(tài)成員函數(shù)返回單例實(shí)例
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr; // 初始化靜態(tài)成員變量

int main() {
    Singleton* singleton1 = Singleton::getInstance();
    Singleton* singleton2 = Singleton::getInstance();

    if (singleton1 == singleton2) {
        std::cout << "singleton1 and singleton2 are the same instance" << std::endl;
    } else {
        std::cout << "singleton1 and singleton2 are different instances" << std::endl;
    }

    return 0;
}

在上面的示例中,Singleton類(lèi)有一個(gè)私有的靜態(tài)成員變量instance用來(lái)存儲(chǔ)單例實(shí)例。靜態(tài)成員函數(shù)getInstance用來(lái)返回單例實(shí)例,當(dāng)實(shí)例為nullptr時(shí)進(jìn)行懶加載,即在第一次調(diào)用getInstance時(shí)創(chuàng)建實(shí)例。在main函數(shù)中,我們通過(guò)調(diào)用getInstance函數(shù)獲取單例實(shí)例,并驗(yàn)證兩個(gè)實(shí)例是否相同。

這樣就實(shí)現(xiàn)了在C++中使用懶加載方式創(chuàng)建單例類(lèi)的方法。

0