In addition to copy constructor and assignment operator C++ got so-called move constructor and assignment operator. First I am gonna show you what copy constructor and assignment operators are:
class A
{
public:
int* some_data;
A()
{
some_data = new int[128];
}
// Copy constructor
A(const A& a)
{
some_data = new int[128];
memcpy(some_data, a.some_data, 128);
}
~A()
{
delete[] some_data;
}
// Assignment operator
A& operator = (const A& a)
{
if (this != &a)
{
delete[] some_data;
some_data = new int[128];
memcpy(some_data, a.some_data, 128);
}
return *this;
}
};
int main()
{
A a1;
A a2(a1); // Copy constructor call
A a3;
a3 = a1; // Assignment operator call
return 0;
}
As you can see both copy constructor and assignment operator do exactly the same thing, they create a copy of other instance of the same class. In the example above, copying maybe slightly optimized using move constructor and move assignment operator:
class A
{
public:
int* some_data;
A()
{
some_data = new int[128];
}
// Move constructor
A(A&& a)
{
some_data = a.some_data;
a.some_data = nullptr;
}
~A()
{
delete[] some_data;
}
// Move assignment operator
A& operator = (A&& a)
{
if (this != &a)
{
delete[] some_data;
some_data = a.some_data;
a.some_data = nullptr;
}
return *this;
}
};
int main()
{
A a1;
A a2(std::move(a1)); // Move constructor call
A a3;
a3 = std::move(a1); // Move assignment operator call
return 0;
}
In other words, move constructor and move assignment operator are merely optimized versions of regular copy constructor and assignment operator.
No comments:
Post a Comment