【发布时间】:2019-10-17 14:09:29
【问题描述】:
std::exchange 可用于实现移动构造函数。这是来自 cppreference.com https://en.cppreference.com/w/cpp/utility/exchange#Notes 的示例。
但是,std::exchange 的可能实现如下所示:
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?
}
现在我的情况:
#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;
}
};
正如我对代码的评论,有机会按行移动或复制
m_str{ std::exchange(other.m_str, {}) }
this->m_str = std::exchange(other.m_str, nullptr);
因此,
- 我是否应该明确地为他们使用
std::move,这样我才能确定 成员是否已 100% 移动到other对象? - 如果是,使用
std::exchange会更冗长吗? 场景?
我正在使用带有编译器标志 C++14 的 Visual Studio 2017。
【问题讨论】:
标签: c++ c++14 move-constructor