Git Product home page Git Product logo

singleton's Introduction

单例模式模板实现


单例模式有两点需要注意:

1. 如何保证多线程安全

std::call_once

定义于头文件 <mutex>
template< class Callable, class... Args > void call_once( std::once_flag& flag, Callable&& f, Args&&... args ); (C++11 起)

准确执行一次可调用 (Callable) 对象 f ,即使同时从多个线程调用。

即使在从多个线程调用时,也保证函数局部静态对象的初始化仅出现一次,这可能比使用 std::call_once 的等价代码更为高效。

2. 如何自动清理单例内部申请的内存

利用了局部静态对象的析构函数释放内存。

用static关键字修饰的局部变量叫静态局部变量,它存储在静态存储区,生命期贯穿整个程序运行期间。

1、全局对象,程序一开始,其构造函数就先被执行(比程序进入点更早);程序即将结束前其析构函数将被执行。

2、局部对象,当对象生成时,其构造函数被执行;当程序流程将离开该对象的声明周期时,其析构函数被执行。

3 、静态(static)对象,当对象生成时其构造函数被执行;当程序将结束时其析构函数才被执行,但比全局对象的析构函数早一步执行。

4、以new方式产生出来的局部对象,当对象生成时其构造函数被执行,析构函数则在对象被delete时执行时执行

3. 编译说明

g++ -std=c++11 -o singleton main.cpp -lpthread 

singleton's People

Contributors

debugviewer avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.