Text provides a code which should call the move constructor. However, it is not getting called. Where the implementation has gone wrong?

32 views Asked by At


As I was going through the C++ book by Siddhartha Rao, I came across the following code (pardon the lack of proper spacing):

 #include <iostream>
 #include <algorithm>
 using namespace std;

 class MyBuffer
 {
public:
 int* myNums;
 unsigned int bufLength;
 
 MyBuffer(unsigned int length)
 {
 bufLength = length;
 cout << "Constructor allocates " << length << " integers" << endl;
 myNums = new int[length]; // allocate memory
 }

 MyBuffer(const MyBuffer& src) // copy constructor
 {
 cout << "Copy constructor creating deep copy" << endl;
 bufLength = src.bufLength;
 myNums = new int[bufLength];
 copy(src.myNums, src.myNums + bufLength, myNums); // deep copy
 }

// move constructor
MyBuffer(MyBuffer&& moveSource)
{
cout << "Move constructor working here!" << endl;   
if(moveSource.myNums != NULL)
{
myNums = moveSource. myNums; // take ownership i.e. ’move’
moveSource.myNums = NULL; // set the move source to NULL
}
}

 ~MyBuffer()
 {
 cout << "Destructor releasing allocated memory" << endl;
 delete[] myNums; // free allocated memory
 }

 void SetValue(unsigned int index, int value)
 {
 if (index < bufLength) // check for bounds
 *(myNums + index) = value;
 }

 void DisplayBuf()
 {
 for (unsigned int counter = 0; counter < bufLength; ++counter)
 cout << *(myNums + counter) << " ";

 cout << endl;
 }
 };

MyBuffer Copy(MyBuffer& source) // function
{
MyBuffer copyForReturn(source.bufLength); // create copy
return copyForReturn; // return by value invokes copy constructor
} 

int main()
{
MyBuffer buf1(5);
MyBuffer buf2 = Copy(buf1); // invokes 1x copy, 1x move constructor
return 0;
}

I can understand that move constructor is implemented to avoid deep copying when returning by value. However, as a check I added this line in the move constructor code: cout << "Move constructor working here!" << endl;
But the thing is that it is not getting printed in the output.
My output is
Constructor allocates 5 integers Constructor allocates 5 integers Destructor releasing allocated memory Destructor releasing allocated memory
Does it mean that move constructor is not getting invoked?

0

There are 0 answers