Temporary variables and copy constructors (ii)

Source: Internet
Author: User

For visual observation, the following code copies the constructor to num+1 the member variable

Class B{int num;public:b (): num (0) {cout << "default constructor" << "  num=" << num <<endl;} B (int n): num (n) {cout << "parameter constructor" << "  num=" << num << Endl;} B (const b &b) {num = b.num+1;cout << copy constructor <<  num= << num << Endl;} /*b (B &&b) {cout << move constructor << Endl;} */b& operator= (const B &b) {cout << assignment operator <<  num= <<b. Num << endl;if (this = = &A MP;B) Return *this;num = B.num;return *this;} ~b () {cout << destructor << "  num=" << num << Endl;}}; b Play (b b) {b bb (+); return BB;} void Main () {{B B1 (1); B B2 = Play (B1);} cout << "-------------------------" << Endl; {B B1; B B2 (ten); b2 = Play (B1);}}


Output:


The results show that after a function call is finished, the local variables generated by the destructor code are first destructor, and then the temporary variables generated by the input parameters are reconstructed, and then the temporary variables generated by the return values are finally reconstructed.



Modify the play function in the above code to compare:

b Play (b b) {b bb (+); return b;} void Main () {{B B1; B B2 = Play (B1);} cout << "-------------------------" << Endl; {B B1; B B2 (ten); b2 = Play (B1);}}

Output:



In the screen output, before the horizontal line, the play return value does not produce a temporary variable, but after the horizontal line has a temporary variable, why??



Temporary variables and copy constructors (ii)

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.