5
using namespace std;

Object returnObject(){
    Object o;  
    return o;  //place A
 }

int main() {
    Object CopiedO=returnObject();  
    return 0;  //Place B
}

the object definition is:

Object::Object() {
    cout<<"Object::Object"<<endl;
}

Object::~Object() {
    cout<<"Object::~Object"<<endl;
}

Object::Object(const Object& object) {
    cout<<"Object::CopyObject"<<endl;
}

the result is:

/*Object::Object
Object::~Object*/

As I understand, both o and CopiedO in will be deconstructed, but why only once Object::~Object be printed?

I think there is no inline and the copied o is copy of o .but it can't print Object::CopyObject

jiafu
  • 6,338
  • 12
  • 49
  • 73
  • 4
    This is a fine example of return value optimisation (RVO) at work. :-) – C. K. Young Jan 10 '14 at 04:32
  • can you give detailed info for it? – jiafu Jan 10 '14 at 04:33
  • http://stackoverflow.com/q/12953127/13 – C. K. Young Jan 10 '14 at 04:34
  • Removed my answer saying it was move semantics. That would not be the case because the default move constructor is not automatically generated when you have a user-defined copy constructor. – Mark Jan 10 '14 at 04:51
  • 1
    You can try split the assignment into two lines: `Object CopiedO; CopiedO = returnObject();` and you will see the difference how the optimization works. – Mine Jan 10 '14 at 05:25

1 Answers1

4

The compiler is eliding the copy. Since it knows that the returned object from the function has as only purpose to initialize CopiedO, it is merging both objects into one and you will see only one construction, one destruction and no copy-constructions.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489