scope - When is a copy constructor called in C++? - Function return -


i'm working through chapter 18 of stroustrup's principles , practice , stuck on 1 part related copy constructors.

i have copy constructor defined as:

x(const x& x) {     out("x(x&)");     val = x.val; } 

x struct. val int value of x. 'out' is:

void out(const string& s) {     cerr << << "->" << s << ": " << val << "\n"; } 

i have following 2 functions defined:

x copy(x a) {     return a; } 

and

x copy2(x a) {     x aa = a;     return aa; } 

in main have:

x loc(4); x loc2 = loc; loc2 = copy(loc); loc2 = copy2(loc); 

when call copy, copy constructor called twice: once copy's parameter scope , once return call. makes sense me.

however, when call copy2, copy constructor still called twice: once function argument , once 'x aa = a.' why isn't called return?

there's no guarantee copy constructors called in c++. in case of return, it's replaced move or elided.

see also: what copy elision , return value optimization?


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -