0

I have the following piece of code:

#include<iostream> using namespace std; class A{ int size; double *arr; public: A(int len):size(len) { cout<<"ctor called"<<endl; arr=new double[size]; } A(const A &rhs) { cout<<"calling copy ctor"<<endl; size=rhs.size; arr=new double[size]; } ~A() { cout<<"calling dtor"<<endl; delete[] arr; arr=NULL; size=0; } }; A createVector() { cout<<"Creating object"<<endl; A a(10); cout<<"returning after creating object a"<<endl; return a; } void foo(A v) { cout<<"Class A object rcvd"<<endl; //return v; } int main() { A a=createVector(); cout<<"a has been rcvd"<<endl; foo(a); return 0; } 

And I have the following output:

Creating object ctor called returning after creating object a a has been rcvd calling copy ctor Class A object rcvd calling dtor calling dtor 

I am having trouble with createVector() function. When I return a object by value,its copy constructor should be called but I am not seeing any output between the lines

returning after creating object a a has been rcvd 

Why copy constructor has not been called??
(when I pass the rcvd object as value to foo(),Copy Constructor gets called)

7
  • 4
    See copy elision. Commented Jul 14, 2018 at 7:29
  • 1
    'When I return a object by value,its copy constructor should be called', not necessarily true. Commented Jul 14, 2018 at 7:30
  • 2
    Also look up NRVO. Commented Jul 14, 2018 at 7:32
  • @songyuanyao The link says "Omits copy- and move- (since C++11)" ,so if I remove the -stdc++=11 flag,I should get the Copy Constructor called,right?? I checked,I am getting the same output. Commented Jul 14, 2018 at 7:49
  • 1
    @aalisha You are misreading the documentation. Move only exists since C++11, that is what '(since C++11)' refers to. Copy elision has always existed. Commented Jul 14, 2018 at 7:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.