I am a C++ newbie. I learned that a function can return by value, but in my code it doesn't seem to work right.
#include "pch.h"
#include <iostream>
class B {
public:
int* ip;
B() : ip(new int(0)) {}
//COPY CTOR
B(B& other){
ip = new int(0);
*ip = *other.ip;
}
//MOVE CTOR
B(B&& other) : ip(NULL){
ip = other.ip;
}
B& operator=(B& other)
{
int* ptr = new int(0);
*ptr = *other.ip;
delete ip;
ip = ptr;
}
B& operator=(B&& other)
{
int* ptr = new int(0);
*ptr = std::move(*other.ip);
delete ip;
ip = ptr;
}
~B() {
delete ip;
ip = NULL;
}
};
B CreateB()
{
B b;
*(b.ip) = 99;
return b;
}
int main()
{
B BObj(CreateB());
std::cout << "B.ip=" << *BObj.ip << std::endl;
system("pause");
return 0;
}
I used visual studio 2019 in debug mode, I stepped in CreateB() and found local object B created. At "return b;" statement debug stepped to Move Constructor B(B&& other) which I figured out this is compiler optimization. Instead of using Copy constructor to create B object from local B object the compiler used Move Constructor. However, after executing Move constructor, debug took me to destructor ~B(). Now the object returned by the function to main was gone. Why didn't the compiler use Copy Ctor then deleted the local object? Thanks!