Singleton C ++ Part 1

Source: Internet
Author: User

Static or global variables

C ++ cannot guarantee the calling sequence and destructor sequence of the constructors of static or global objects. Therefore, if there are multiple Singleton classes implemented using this method in the program, there is another constructor dependency and destructor dependency between them, which will cause disastrous consequences. Therefore, this implementation is appropriate only when there is certainly no constructor or destructor dependency.

> Advantages Simple implementation and multi-thread security
> Disadvantages If the creation sequence of multiple Singleton objects is dependent, do not use it. It is not lazy loading, which is a waste.
Meyers Singleton controls the construction order, but does not control the structure order.

Scott Meyer proposed a solution in <strong tive C ++> 3rd Item4 when moving the non-local static variable to the static method to become the local static variable. C ++ makes sure that this static variable is created only when the first static method is called. But here is a question: the order of creation can be controlled, but what about the structure order? We only know that at the end of the process, the local static variable will be destructed and executed in reverse order of creation. If the destructor of several Singleton classes also have dependencies, and the dependency order conflicts with the LIFO sequence, the dead-reference problem will occur.

> Advantages It is easy to implement. It is created only when used, saving a lot of time.
> Disadvantages Multithreading is not secure. Be careful when multiple Singleton objects have dependency on the Structure sequence.
The DCLP 98 standard is unreliable, and the 0x standard is reliable.

DCLP is Double-checked locking pattern. It is used to ensure that only Singleton objects are created in a multi-threaded environment. No lock is required for the first check, but the second check and creation object must be locked. Note that the compiler may optimize the code, resulting in invalid DCLP mode. Therefore, you must use volatile to modify the T * pInstance variable. Let's take a look at the DCLP implementation code:

 > class Singleton {> public:>     static Singleton* instance() {>         if (pInstance == 0) {>             Lock lock;>             if (pInstance == 0) {>                 pInstance = new Singleton;>             }>         }
>         return pInstance;>     }> private:>     static Singleton * volatile pInstance;>     Singleton(){>     }> };> 


Under the c ++ 98 standard, this is unreliable. There are three reasons:
1. The execution sequence is not guaranteed. The compiler optimizes the code to change the execution sequence.
PInstance = new Singleton; this statement is completed in three steps: 1. allocate memory, 2. call the constructor to create an object on the allocated memory. 3. assign the object to the pointer pInstance. however, this order may be changed to 1, 3, and 2. If thread A judges if (pInstance = 0) when the first condition of thread B is completed at thread 1 and 3, the lock cannot be protected. Line B considers that pInstance has already pointed to a valid object and can be used. Hey, disaster. The main reason is that the C ++ 98 standard does not contain multithreading. It is assumed that it is a single thread, and the optimization behavior of the compiler ignores the multi-threaded environment. Therefore, the generated optimization code may be removed or changed in order. We have no way to solve this problem by using the standard c ++ language in the 98 standard. We can only use the platform-related multi-threaded APIs and compatible compilers to solve this problem. Therefore, this problem is essentially based on the 98 standard.
2. volatile does not help with the execution sequence.
3. In A multi-processor system, the sequence of variable values may be different from the sequence of variable values written by A processor.

For more information, see Scott Meyers and Andrei Alexandrescu: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf.
Technology is always evolving. The introduction of the 2011 standard has brought a new dawn to DCLP. Can it be used? Wait and see.

Let's draw a conclusion:

> Disadvantages Unavailable under 98 Standard
> Advantages Let's get an education, including Andrei and Scott meyer making mistakes.



Andrei said 4.11 scott meyer elaborated on the 0x standard, because of the thread concept, memory model, sequence point is replaced by sequenced before and happens before, and atomic, etc, DCLP can be revived again.
Http://cppandbeyond.com/2011/04/11/session-announcement-the-c0x-memory-model-and-why-you-care/
What did you talk about? I have not found any documentation.

Simple lock

So I went back to the old-fashioned lock solution. In fact, pay attention to the call, which can improve the efficiency.

 > class Singleton {> public:>     static Singleton* instance() {>         Lock lock;>         if (pInstance == 0) {>             pInstance = new Singleton;>         }
>         return pInstance;>     }> private:>     static Singleton * volatile pInstance;>     Singleton(){>     }> };> 

When calling, the customer obtains Singleton * p = Singleton: instance () at the beginning of each thread. This p variable will be used in the future. It should be said that it can effectively reduce the chance of synchronization. Avoid frequent calls to Singleton: instance ()->.

> Advantages Simple implementation and thread security
> Disadvantages The customer needs to be aware and follow the principle of less calls.

 

Create a Single

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.