I am reading about copy constru开发者_如何学Pythonctor in C++
It was mentioned that an object is passed usuing call by value and return by values constructs a temporary objects that are never seen by the user. My understanding is that when we call by val for example
myclass b;
void myfunc(myclass c) {} //c(b) copy constructor is called.
Where temporary object is created?
Thanks!
The copy is created in the function scope of myfunc()
. That is, c
is in scope of the entire function, which includes (and is slightly larger than) the function body. The copy is destroyed when the function returns, i.e. at the semicolon of myfunc(b);
.
In the case of pass-by-value, a copy is made into the argument (rather than the temporary), so in the particular code in your example, there will be two objects:
myclass b;
myfunc( b ); // b is copied to argument "c" by means of the copy constructor
In the case of return by value, things are a bit more complex, in the code:
type f() {
type tmp;
return tmp; // copies into temporary (again, copy constructor)
}
int main() {
type x = f(); // copies from temporary into x (copy constructor)
x = f(); // copies from temporary into x (assignment operator)
}
there are in theory 3 objects of type type
. The compiler will create space for a type
object before calling f
in a location that is defined by the calling convention (this will be where the temporary is created), then the function is called and tmp
is created inside f
, it gets copied to the temporary in the return statement. Finally the temporary is copied to the x
variable in main
.
In many cases, though, the compiler can optimize away the temporaries by carefully choosing the locations of the variables. Most compilers will be able to optimize 2 of the 3 objects away in the previous example.
For a longer description you can read these:
- http://definedbehavior.blogspot.com/2011/08/value-semantics-nrvo.html
- http://definedbehavior.blogspot.com/2011/08/value-semantics-copy-elision.html
精彩评论