Sep 4, 2011

[C++] Copy Constructor optimization. [draft]

Copy constructor will be called if a function return by value.
[Inside the C++ Object Model (Stanley B. Lippman, 1996)]


However, some compiler optimize this by not calling copy constructor for
returning the local stack object variable.

#include <stddef.h>
#include <iostream>
#include <ostream>
#include <cstdio>
using namespace std;

class Verbalsaint{
  int a;
public:
  Verbalsaint(){
    
  }
  Verbalsaint(const Verbalsaint& rval){
    cout <<"in Constructor" << endl;
    a = rval.a;
  }
  Verbalsaint& operator=(const Verbalsaint& rval){
    cout <<"in operator =" << endl;
    a = rval.a;
  }
};

Verbalsaint callme(){  
  Verbalsaint b;
  return b;
}

int main(){  
  Verbalsaint a=callme();  
}

Reference:
What about returning a local variable by value?

Named Return Value Optimization in Visual C++ 2005



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.