从零开始学C++之对象的使用(三):static 与单例模式、auto_ptr与单例模式、const 用法小结、mutable修饰符

本文介绍了C++中的单例模式,讲解了如何利用static解决对象生命周期问题,以及单例模式在多线程环境下的线程安全性。此外,还探讨了const成员函数、const对象的特性,并对const用法进行了总结,包括mutable修饰符的作用。
摘要由CSDN通过智能技术生成

一、static 与单例模式

单例模式也就是简单的一种设计模式,它需要:

保证一个类只有一个实例,并提供一个全局访问点

禁止拷贝

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
using  namespace std;

class Singleton
{
public:
     static Singleton *GetInstance()
    {
         if (instance_ ==  NULL)
        {
            instance_ =  new Singleton;
        }
         return instance_;
    }

    ~Singleton()
    {
        cout <<  "~Singleton ..." << endl;
    }
private:
    Singleton( const Singleton &other);
    Singleton & operator=( const Singleton &other);
    Singleton()
    {
        cout <<  "Singleton ..." << endl;
    }
     static Singleton *instance_;
};

Singleton *Singleton::instance_;

int main( void)
{
     //Singleton s1;
     //Singleton s2;

    Singleton *s1 = Singleton::GetInstance();
    Singleton *s2 = Singleton::GetInstance();

     //Singleton s3(*s1);        // 调用拷贝构造函数

     return  0;
}


上述程序虽然调用了两个GetInstance函数,但只调用一次构造函数,即创建一个对象。将赋值运算符和拷贝构造函数声明为私有,禁止拷贝。但程序存在一个问题就是对象生存期到时不会被析构。


为了解决对象不会被析构的问题,可以使用一个静态的嵌套类对象来解决:

 C++ Code 
1
2
3
4
5
6
7
8
9
1
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值