Initialize static variables in C ++ functions and analyze the structure order.

Source: Internet
Author: User

There are the following classes:

class base{public:base(char* pStr){m_pStr = pStr;cout << pStr << " Constructor!" << endl;}~base(){cout << m_pStr << " Destructor!" << endl;}void fund(char* pStr){if (pStr != NULL){static base b(pStr);}}void fund2(){static base e("e");}private:char* m_pStr;};base glb("global");

1. The following call methods are available:

int main(){base loc("local");return 0;}

 

What is the output?

Answer:

Global Constructor!

Local Constructor!

Local Destructor!

Global Destructor!

 

Note that the static variable in the function is not initialized because the function is not called ~

Next, we will use the following code:

 

int main(){base d("d");int i;cin >> i;if (i == 0){d.fund(NULL);d.fund("R1");d.fund2();}else{d.fund2();d.fund("R2");}return 0;}

 

When the user inputs 0

Global Constructor!

Local Constructor!

R1 Constructor!

E Constructor!

Local Destructor!

E Destructor!

R1 Destructor!

Global Destructor!

 

When the user input is not 0

Global Constructor!

Local Constructor!

E Constructor!

R2 Constructor!

Local Destructor!

R2 Destructor!

E Destructor!

Global Destructor!

 

It can be seen that static variables can be executed only when the user enters the initialization Code for the first time, and the execution process can be changed according to user input, you can even follow the correct "create first and then destroy!

 

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.