C ++ temporary object

Source: Internet
Author: User

The book says that temporary objects are generated when parameters are passed by value and return values are passed by value. It is better to understand the temporary variables generated when the function transfers parameters by value, it is actually the generation of local variables of function parameters. There are two situations in which the returned value generates a temporary variable.

  1   Class  Test {
2 Static Int I;
3   Public :
4 Test ()
5 {
6 Cout < " Ctor " < Endl;
7 }
8 Test ( Const Test & Test)
9 {
10 Cout < " Copy ctor " < Endl;
11 }
12 ~ Test (){
13
14 Cout < " Destory .. " < Endl;
15 }
16 Void Print ()
17 {
18
19 }
20 };
21
22
23 Test F (test X)
24 {
25 Return X;
26
27 }

 

 

Case 1:

Int main ()
{
Test T1;

Test t2 = f (T1 );

 

Return 0;
}

In this case, T2 is directly constructed by the copy constructor of function f, without generating temporary variables.

 

Case 2

Int main ()
{
Test T1;

Test T2;

T2 = f (T1 );

 

Return 0;
}

In this case, a temporary variable is generated at the return, which is parsed after being assigned to T2. F is also destructed.

 

 

 

 

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.