Skip to content

Commit 3f3bb5f

Browse files
author
wintel2014
committed
1. Both of "const reference" and "right reference" can associate with the object returned by function
2. the object's life returned by function is extended by reference, same to the reference
1 parent e7ce4f2 commit 3f3bb5f

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

C++/C++11/Reference/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
g++ reference_lifecycle.cpp -std=c++11 -fno-elide-constructors -o reference_lifecycle_noRVO
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
int g_constructCount=0;
5+
int g_copyConstructCount=0;
6+
int g_destructCount=0;
7+
struct A
8+
{
9+
A(){
10+
cout<<"["<<this<<"]"<<" construct: "<<++g_constructCount<<endl;
11+
}
12+
13+
A(const A& a)
14+
{
15+
cout<<"copy construct: "<<++g_copyConstructCount <<&a<<"->"<<this<<endl;
16+
}
17+
~A()
18+
{
19+
cout<<"["<<this<<"]"<<" destruct: "<<++g_destructCount<<endl;
20+
}
21+
};
22+
23+
A GetA()
24+
{
25+
A a;
26+
return a;
27+
}
28+
29+
int main() {
30+
/* error: invalid initialization of non-const reference of type ¡®A&¡¯ from an rvalue of type ¡®A¡¯
31+
A& a = GetA();
32+
*/
33+
/*
34+
[0x7ffc9e450d9f] construct: 1
35+
copy construct: 10x7ffc9e450d9f->0x7ffc9e450dcf
36+
[0x7ffc9e450d9f] destruct: 1
37+
copy construct: 20x7ffc9e450dcf->0x7ffc9e450dce
38+
[0x7ffc9e450dcf] destruct: 2
39+
[0x7ffc9e450dce] destruct: 3
40+
A a = GetA();
41+
*/
42+
A&& a = GetA();
43+
return 0;
44+
}

0 commit comments

Comments
 (0)