如何对没有复制构造函数的对象使用std::sort
How can I use std::sort with objects that have no copy constructor?
我试图对包含不可复制可构造或默认可构造(但可移动可构造)对象的向量进行排序,但我遇到了编译器无法为swap
找到有效函数的错误。我以为有一个move构造函数就足够了。我在这里错过了什么?
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
尝试的(不仅仅是移动构造)。请注意,由于存在用户提供的复制构造函数以及用户提供的移动构造函数(即使它们是delete
-ed),因此禁止编译器生成移动赋值运算符。示例:
#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;
});
}
在Coliru上直播
Howard Hinnant(C++11中移动语义的主要贡献者)的幻灯片非常有用,还有Scott Meyers的Effective Modern C++中的项目17:理解特殊成员函数生成。
相关文章:
- 将对象移动到std::shared_ptr
- 使用std::函数映射对象方法
- 使用"std::unordereded_map"映射到"std::list"对象
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 当使用透明的std函数对象时,我们还需要写空的尖括号吗
- 如何使用std::min和std::less返回对象
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- C++11 中不同类型的对象的 std::array 的替代方案
- 返回一个带有 std::move 的对象并链接函数
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- std::string 的对象真的可以移动吗?
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- 即发即弃 std::线程对象清理自身
- 为什么当对象std ::向量被声明但从未使用时,编译器不会发出警告
- C++是保证在基本对象std::swap之后有效的派生对象数据
- 从自定义对象- std:unique的向量中消除重复项会导致崩溃
- 为什么我得到这个奇怪的错误时,试图添加一个重复的对象std::set
- 查找投掷对象 std::out_of_range
- 对象 std::shared_ptr 是否可以通过其 std::weak_ptr 找到