Use static to share a variable among multiple instances of the class

Source: Internet
Author: User

For more information, see Section 12.6 of C ++ primer.

Summarize several things that need to be done:

1. Define static members in the. h file, for example, static int test_num;

2. initialize this member in the. cpp file, for example, int class_name: test_num = 0;

In this way, you can use static members in the class just like using common members.

= ====

For static members that need to be processed during initialization (if you need to fill in data to hashmap members ), an optional method is to initialize and destroy classes in class constructor and destructor.

Maintain a static variable to record the number of instance objects of the current class. Note: If you implement copy and operater = of the class, remember to add 1 to the counter in these two places.

In the constructor, check whether the member has completed initialization and related operations. If not, perform initialization and related operations. At the same time, add the counter to 1.

Check whether the counter is equal to 0 in the destructor. If the counter is equal to 0, destroy the corresponding static member.

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.