我正在尝试对包含不能复制构造或默认构造(但可移动构造)的对象的向量进行排序,但是遇到关于编译器无法为其找到有效函数的错误swap
。我认为拥有一个移动构造函数就足够了。我在这里想念什么?
class MyType {
public:
MyType(bool a) {}
MyType(const MyType& that) = delete;
MyType(MyType&& that) = default;
};
int main(void) {
vector<MyType> v;
v.emplace_back(true);
sort(v.begin(), v.end(), [](MyType const& l, MyType const& r) {
return true;
});
}
您需要显式定义移动分配运算符,因为这std::sort
也是尝试的操作(不仅仅是移动构造)。请注意,由于存在用户提供的复制构造函数以及存在用户提供的移动构造函数(即使它们是-ed),因此禁止生成移动分配运算符的编译器delete
。例:
#include <vector>
#include <algorithm>
class MyType {
public:
MyType(bool a) {}
MyType(const MyType& that) = delete;
MyType(MyType&& that) = default;
MyType& operator=(MyType&&) = default; // need this, adapt to your own need
};
int main(void) {
std::vector<MyType> v;
v.emplace_back(true);
std::sort(v.begin(), v.end(), [](MyType const& l, MyType const& r) {
return true;
});
}
该滑动通过霍华德Hinnant(欣南特)(的主要贡献者在C ++ 11移动语义)是超级有用,以及第17项:理解特殊成员函数生成从有效的现代C ++斯科特迈尔斯。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句