use*_*147 8 c++ copy move-semantics c++20
According to cppreference, std::copyable is defined as follows:
template <class T>
concept copyable =
std::copy_constructible<T> &&
std::movable<T> && // <-- !!
std::assignable_from<T&, T&> &&
std::assignable_from<T&, const T&> &&
std::assignable_from<T&, const T>;
Run Code Online (Sandbox Code Playgroud)
I'm wondering why a copyable object should be also movable. Just think about a global variable that is accessed by several functions. While it makes sense to copy that variable (for example to save its state before calling another function) it makes no sense, and actually would be very bad, to move it since other functions might not know that that variable is currently in an unspecified state. So why exactly does std::copyable subsume std::movable ?
这来自两个事实。首先,即使您没有定义移动构造函数 + 移动赋值,如果您定义了复制函数,您仍然可以从右值引用构造/分配对象。看看这个例子:
#include <utility>
struct foo {
foo() = default;
foo(const foo&) = default;
foo& operator=(const foo&) = default;
};
int main()
{
foo f;
foo b = std::move(f);
}
Run Code Online (Sandbox Code Playgroud)
其次(也许更重要的是),可复制类型始终可以(或根据现在的标准必须)以某种方式可移动。如果对象是可复制的,那么移动的最坏情况就是复制内部数据。
请注意,由于我声明了复制构造函数,编译器不会生成默认的移动构造函数。
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |