我可以从向量的开头移动对象吗?为什么不?
Can I move an object from the beginning of a vector? Why not?
This 不编译。为什么?
#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;
}
错误:
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
是否可以从 vector 移动对象(不调用复制赋值运算符)?
This does not compile. Why?
因为你的结构test_s
需要一个移动构造函数(或复制构造函数)。
声明:
test_s ss = std::move(v.front());
构造对象ss
。虽然您看到 =
标志,但这不是 作业 。
但是,您已经在结构中定义了一个移动赋值。
根据this table,当用户定义移动赋值时,移动构造函数不是由编译器。此外,move 操作应该在副本上 "fallback" 但是(正如你在 table 中看到的),copy constructor 被隐式删除(正如您的编译器所建议的那样)。
Is it possible to move an object from vector(without the call to copy assignment operator)?
嗯,是的。
您应该为 class 定义自己的 移动构造函数 。
实际上,您应该遵循 rule of five.
注:
另请注意,您的代码有一个 未定义的行为 ,因为您试图访问向量中不存在的元素(正如一些评论所指出的)。
This 不编译。为什么?
#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;
}
错误:
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
是否可以从 vector 移动对象(不调用复制赋值运算符)?
This does not compile. Why?
因为你的结构test_s
需要一个移动构造函数(或复制构造函数)。
声明:
test_s ss = std::move(v.front());
构造对象ss
。虽然您看到 =
标志,但这不是 作业 。
但是,您已经在结构中定义了一个移动赋值。
根据this table,当用户定义移动赋值时,移动构造函数不是由编译器。此外,move 操作应该在副本上 "fallback" 但是(正如你在 table 中看到的),copy constructor 被隐式删除(正如您的编译器所建议的那样)。
Is it possible to move an object from vector(without the call to copy assignment operator)?
嗯,是的。
您应该为 class 定义自己的 移动构造函数 。 实际上,您应该遵循 rule of five.
注: 另请注意,您的代码有一个 未定义的行为 ,因为您试图访问向量中不存在的元素(正如一些评论所指出的)。