I have the following 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(A&& rhs) { cout<<"caling move constructor"<<endl; size=rhs.size; arr=rhs.arr; rhs.arr=nullptr; } ~A() { cout<<"Calling Dtor"<<endl; delete[] arr; size=0; arr=NULL; } }; A createVector() { cout<<"Creating object"<<endl; A a(20); cout<<"returning after creating object a"<<endl; return (a); } void foo(A v) { cout<<"Class A object rcvd"<<endl; return; } int main() { //cout<<"a has been rcvd"<<endl; foo(createVector()); return 0; } I have passed a temporary object of Type 'A'(which has been returned by another function).I am expecting a call to Move constructor.But I am getting the below output:
Creating object ctor called returning after creating object a Class A object rcvd Calling Dtor Why there is no call to Move Constructor?? Also if change the code as following:
foo(createVector())----->foo(move(createVector())); I get the following output:
Creating object ctor called returning after creating object a caling move constructor Class A object rcvd Calling Dtor Calling Dtor Why there is a call to Destructor two times??
size = 0; arr = NULL;in the destructor is pointless. The object is going away; those members won't exist after the destructor exits.