Singleton class implementation using shared_ptr

前端 未结 3 1262
遇见更好的自我
遇见更好的自我 2021-02-09 17:58
#include 
#include 

using namespace std;

class Demo {
    static shared_ptr d;
    Demo(){}
public:    
    static shared_ptr         


        
3条回答
  •  时光取名叫无心
    2021-02-09 18:34

    Some comments from 1 to help with the discussion. Static variable will be destroyed uppon exit of the application, so we don't need to use the smart pointer at this stage as mentioned above.

    "If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with std::call_once).

    Note: usual implementations of this feature use variants of the double-checked locking pattern, which reduces runtime overhead for already-initialized local statics to a single non-atomic boolean comparison. (since C++11)

    The destructor for a block-scope static variable is called at program exit, but only if the initialization took place successfully. "

提交回复
热议问题