简体   繁体   中英

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

I'm working through chapter 18 of Stroustrup's Principles and Practice and am stuck on one part related to copy constructors.

I have a copy constructor defined as:

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

X is a struct. val is just an int value of X. 'out' is:

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

I also have the following 2 functions defined:

X copy(X a) {
    return a;
}

and

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

In main I have:

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

When I just call copy, the copy constructor is called twice: once for copy's parameter scope and once for the return call. This makes sense to me.

However, when I call copy2, the copy constructor is still just called twice: once for the function argument and once for 'X aa = a.' Why isn't it also called for the return?

There's no guarantee that copy constructors will be called in C++. In the case of return, it's likely to be replaced by a move or completely elided.

See also: What are copy elision and return value optimization?

Since you are returning a local variable, move semantics apply.

Optimizations make copying, moving and returning even more elaborate, see Tatuyuki Ishi's answer.

Here are some good examples for move semantics for return statements .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM