我可以从矢量的开头移动对象吗?为什么不?

1 c++ move-semantics

不会编译。为什么?

#include <iostream>
#include <vector>

struct test_s {
    int a;

    test_s& operator=(test_s &&ts) {
        a = ts.a;
        ts.a = 0;
        return *this;
    }
};

int main ()
{
  std::vector<test_s> v;

  test_s ss = std::move(v.front());

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

source_file.cpp:20:10: error: call to implicitly-deleted copy constructor of 'test_s'
  test_s ss = std::move(v.front());
         ^    ~~~~~~~~~~~~~~~~~~~~
source_file.cpp:9:13: note: copy constructor is implicitly deleted because 'test_s' has a user-declared move assignment operator
    test_s& operator=(test_s &&ts) {
            ^
1 error generated
Run Code Online (Sandbox Code Playgroud)

是否可以从矢量移动对象(无需调用复制赋值运算符)?

Bia*_*sta 5

这不会编译。为什么?

因为您的结构test_s需要move构造函数(或copy构造函数)。

该声明:

test_s ss = std::move(v.front());
Run Code Online (Sandbox Code Playgroud)

构造对象ss。尽管您看到了=标志,但这不是作业

但是,您已经在结构中定义了移动分配

根据该表,当用户定义移动分配时,编译器不会提供移动构造函数。此外,移动操作应在副本上“回退”,但是(如您在表中所见),副本构造函数被隐式删除(正如编译器建议的那样)。

是否可以从矢量移动对象(无需调用复制赋值运算符)?

嗯,是。

您应该为类定义自己的move构造函数。实际上,您应该遵循5规则

注意: 还请注意,当您尝试访问向量中不存在的元素时(如某些注释所指出的那样),代码具有未定义的行为