在从 stl 向量的派生类中实现移动语义
Implement the move semantic in a derived class from stl vector
我有以下继承STL向量的类:
class Vec : public vector<int> {
public:
Vec() : vector<int>() {}
Vec(size_t N) : vector<int>(N) {}
Vec(Vec&& v) : vector<int>(v) {}
Vec(const Vec&) = delete;
Vec& operator = (const Vec&) = delete;
};
基本上,Vec
是 STL 向量的包装器,其中禁用了 copy
构造函数和赋值。但是,看起来移动构造函数无法通过以下方式正常运行:
Vec a(100);
Vec b(move(a))
cout << a.size() << " " << b.size(); // here I got "100 100"
我的Vec
包装有问题吗?此外,如何实现Vec
类的移动分配,以便通过移动分配Vec b = a
?我正在想象类似以下内容,但它不起作用:(
Vec& operator = (Vec&& rhs) {
return move(*this);
}
还有一个问题。在实现移动语义时,我们是否应该始终避免使用const
关键字?任何帮助将不胜感激。
Vec(Vec&& v) : vector<int>{std::move(v)} // You missed a `std::move` here
{
}
Vec& operator=(Vec&& v)
{
vector<int>::operator=(std::move(v)); // Selects base class function
return *this;
}
演示
在您的 Vec 移动构造函数中,您正在使用矢量复制构造函数。只是追查这个:
Vec(Vec&& v) : vector<int>(move(v)) {};
它会正常工作。
相关文章:
- 如何为具有私有成员的派生类实现移动构造函数
- 有没有办法实现移动消除
- 将函数及其实现移动到与主文件不同的文件(.hpp 和 .cpp)时,性能会受到很大影响
- 如何使用继承(抽象基类)实现移动构造函数和移动赋值运算符
- 无法使用迭代器擦除矢量元素,矢量元素实现移动构造函数
- 交换对象不实现移动语义时的交换函数
- 每次复制实现移动分配的非 const 对象时,我是否总是获得移动语义
- 使用 unique_ptr<> 实现移动构造函数和赋值
- 如何在模板类中实现移动语义
- 根据析构函数和移动构造函数实现移动赋值
- C++ 向量实现 - 移动构造函数 - 移动与前进
- 在从 stl 向量的派生类中实现移动语义
- 在什么场景中,我应该明确需要实现移动构造函数和移动赋值运算符
- 在 C++98 中实现移动构造函数和移动赋值运算符以获得更好的性能
- 我应该在什么条件下考虑实现移动构造函数和移动运算符
- 为数组类实现移动构造函数(右值引用)
- 为带有std::vector成员的std::vector的类实现移动语义的正确方法
- std::实现移动
- 如何实现移动场景
- 我们如何在没有循环的情况下将实现移动到多个头文件