The std::exchange can be used to impliment the move constructors. Here is an example from the cppreference.com https://en.cppreference.com/w/cpp/utility/exchange#Notes.
However, the possible implimenation of the std::exchange looks like this:
template<class T, class U = T>
T exchange(T& obj, U&& new_value)
{
T old_value = std::move(obj);
obj = std::forward<U>(new_value);
return old_value; // can be copy (until C++17) or a move (C++17), right?
}
Now my situation:
#include <string>
#include <utility>
struct MyClass
{
std::string m_str;
// some other non-primitive members of the class
MyClass(MyClass&& other) : m_str{ std::exchange(other.m_str, {}) } // enough?
// or
// : m_str{ std::move(std::exchange(other.m_str, {})) }
// ^^^^^^^^^^ do i need to move?
{}
MyClass& operator=(MyClass&& other)
{
this->m_str = std::exchange(other.m_str, {}); // enough?
// or
// this->m_str = std::move( std::exchange(other.m_str, {}) );
// ^^^^^^^^^^ do I need to move?
return *this;
}
};
As I commented on the code, there is a chance for move or copy by the lines
m_str{ std::exchange(other.m_str, {}) }
this->m_str = std::exchange(other.m_str, nullptr);
Therefore,
- should I use explicitly
std::movefor them, so that I can make sure that the members have been 100% moved to theotherobject? - If Yes, will it be more verbous to use
std::exchangefor this scenario?
I am using visual studio 2017 with compiler flag C++14.