Here is my code, I got instance a, and b created by Move constructor base on a.
Class Move has one variable data.
I think "move" make b "point to" a, so "a.data" and "b.data" should have the same addr, but in my case, the addr is not same. Why this happens?
// C++ program with declaring the
// move constructor
#include <iostream>
#include <vector>
usingnamespace std;
// Move Class
class Move {
public:
int* data;
// Constructor
Move(int d)
{
// Declare object in the heap
data = newint;
*data = d;
cout << "Constructor is called for "
<< d << endl;
};
// Copy Constructor
Move(const Move& source)
: Move{ *source.data }
{
// Copying the data by making
// deep copy
cout << "Copy Constructor is called -"
<< "Deep copy for "
<< *source.data
<< endl;
}
// Move Constructor
Move(Move&& source)
: data{ source.data }
{
cout << "Move Constructor for "
<< *source.data << endl;
source.data = nullptr;
}
// Destructor
~Move()
{
if (data != nullptr)
// If pointer is not pointing
// to nullptr
cout << "Destructor is called for "
<< *data << endl;
else
// If pointer is pointing
// to nullptr
cout << "Destructor is called"
<< " for nullptr "
<< endl;
// Free up the memory assigned to
// The data member of the object
delete data;
}
};
// Driver Code
int main()
{
// Vector of Move Class
//vector<Move> vec;
//// Inserting Object of Move Class
//vec.push_back(Move{ 10 });
//vec.push_back(Move{ 20 });
Move a(10);
cout << &(a.data) << endl;
Move b = move(a);
cout << &(b.data) << endl;
return 0;
}
The issue is in main(). &(a.data), &(b.data) is the address of the .data member within the variable - not the memory address held within data. The address of the .data member will be different for each variable - but for move(), the memory pointed to will be the same.