Whenever a temporary class object is copied using a copy constructor, and this object and the copy have the same cvunqualified type, an implementation is permitted to treat the original and the copy as two different ways of referring to the same object and not perform a copy at all, even if the class copy constructor or destructor have side effects. For a function with a class return type, if the expression in the return statement is the name of a local object, and the cvunqualified type of the local object is the same as the function return type, an implementation is permitted to omit creating the temporary object to hold the function return value, even if the class copy constructor or destructor has side effects. In these cases, the object is destroyed at the later of times when the original and the copy would have been destroyed without the optimization. 111) [Example:
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Thing {
public:
Thing();
~Thing();
Thing(const Thing&);
Thing operator=(const Thing&);
void fun();
};
Thing f() {
Thing t;
return t;
}
Thing t2 = f(); |
Here t does not need to be copied when returning from f. The return value of f may be constructed
directly into the object t2. ]
__________________
111) Because only one object is destroyed instead of two, and one copy constructor is not executed, there is still one object destroyed
for each one constructed.
Partager