S
Srini
Hello all,
I was going thru the GotW archives where I had a doubt in this
particular item.
http://www.gotw.ca/gotw/027.htm
There is a mention about a subtle change to the standard in July 1997.
According to that, the only places a compiler can eliminate making copy
of objects is in case of return value optimization and temporary
objects. For a piece of code like -
bool g(X x) {
// ...
return true; // or false
}
bool f(X x) {
return g(x);
}
// user code
X xObj;
bool truth = f(xObj);
The compiler cannot optimize the code to construct the copy of 'xObj'
in function 'g' directly. It has to perform 2 copies - one from 'xObj'
of user code to 'x' of function 'f' and then another from 'x' of
funtion 'f' to 'x' of function 'g'. As to the reason for why this was
done, a note at the bottom of the page says -
"This change was necessary to avoid the problems that can come up when
compilers are permitted to wantonly elide copy construction, especially
when copy construction has side effects. There are cases where
reasonable code may rely on the number of copies actually made of an
object."
I'm not very clear about this reason. What kind of side-effects of copy
construction can lead to problems. An example would help me understand
this better. Also, if code relies on the actual number of copies made
of an object, would it not be affected by return value optimization?
Regards,
Srini
I was going thru the GotW archives where I had a doubt in this
particular item.
http://www.gotw.ca/gotw/027.htm
There is a mention about a subtle change to the standard in July 1997.
According to that, the only places a compiler can eliminate making copy
of objects is in case of return value optimization and temporary
objects. For a piece of code like -
bool g(X x) {
// ...
return true; // or false
}
bool f(X x) {
return g(x);
}
// user code
X xObj;
bool truth = f(xObj);
The compiler cannot optimize the code to construct the copy of 'xObj'
in function 'g' directly. It has to perform 2 copies - one from 'xObj'
of user code to 'x' of function 'f' and then another from 'x' of
funtion 'f' to 'x' of function 'g'. As to the reason for why this was
done, a note at the bottom of the page says -
"This change was necessary to avoid the problems that can come up when
compilers are permitted to wantonly elide copy construction, especially
when copy construction has side effects. There are cases where
reasonable code may rely on the number of copies actually made of an
object."
I'm not very clear about this reason. What kind of side-effects of copy
construction can lead to problems. An example would help me understand
this better. Also, if code relies on the actual number of copies made
of an object, would it not be affected by return value optimization?
Regards,
Srini