I'm a C++ newbie, and this is probably a stupid question to ask.
I'm reading a book Data Structures and Algorithm Analysis in C++, where the implementation of a user-defined vector class template was provided.
Here's a snippet of it
// Move Constructor
Vector(Vector&& source) noexcept
: size(source.size), capacity(source.capacity), objects(source.objects)
{
source.objects = nullptr;
source.size = 0;
source.capacity = 0;
}
// Move Assignment
Vector & operator= (Vector&& source) noexcept
{
std::swap(size, source.size);
std::swap(capacity, source.capacity);
std::swap(objects, source.objects);
return *this;
}
I figure some operations are redundant, here's my draft↓
// Move Constructor
Vector(Vector&& source) noexcept
: size(source.size), capacity(source.capacity), objects(source.objects)
{
source.objects = nullptr; // Forget the rest two integers
}
// Move Assignment
Vector & operator= (Vector&& source) noexcept
{
size = source.size; // std::swap is unnecessary
capacity = source.capacity;
std::swap(objects, source.objects);
return *this;
}
Why would the author use std::swap here? To my knowledge, std::swap is implemented using move semantics, which is introduced to fix smart pointers, not for basic data types.
size and capacity are merely integers, std::swap actually calls std::move and does the assignment three times, thus slowing down the performance since an ordinary assignment would do the same thing. Or is there any benefit of doing so?
Re: Much obliged for the comments folks, I can understand that there is no penalty for using std::move, but swapping means three assignments, right? Can I just use a = operator instead?