如何通过 std::vector 子类的重载赋值运算符进行深度复制<T>?
How to do deep copy by overloaded assignment operator of subclass of std::vector<T>?
我有一个从std::vector<unsigned int>
派生的类Step
。我需要重载赋值运算符,因为深拷贝用于赋值从静态方法返回的值。我无法弄清楚我应该如何将rhv
的所有元素复制到作业中的this
:
class Step : public std::vector<unsigned int>
{
public:
friend std::ostream& operator<<(std::ostream& outStream, const Step& step);
Step& operator =(const Step& rhv);
static Step fromString(const std::string &input);
// Something like: Step x = Step::fromString("12 13 14 15 16");
private:
double time;
double pause;
unsigned int id;
std::string name;
};
然后重载=
:
Step& Step::operator =(const Step& rhv)
{
time = rhv.time;
pause = rhv.pause;
id = rhv.id;
// How should I copy contents of rhv to `this` safely?
return *this;
}
我不是 100% 确定你的问题,但我认为你问的是关于打电话给父operator=
.在这种情况下,您有两种选择:
std::vector<unsigned int>::operator=(rhv); //either explicitly call the parent assignment op
*static_cast<std::vector<unsigned int>*>(this) = rhv; //or cast this to parentclass and call assignment on that
当然,在您向我们展示的代码中,您不会进行任何手动资源处理,所以我不明白为什么要编写自己的赋值运算符,编译器生成的运算符应该可以正常工作。此外,如果您编写自己的赋值运算符,您可能希望遵循三法则并编写自己的复制构造函数和析构函数(至少在 C++03 中,由于可移动但不可复制的类,C++11 可能会有点不同(。
作为另一个旁注:大多数标准库类不是为派生而设计的,因此您可能需要重新考虑您的设计,要求您继承表单std::vector
从标准容器继承通常被认为是一个坏主意,因为它们不是为用作基类而设计的(没有虚拟析构函数等(。几乎每种情况下都首选构图。
假设您决定进入此雷区,则可以使用 static_cast
调用父赋值运算符。
*static_cast<std::vector<unsigned int>*>(this) = rhv;
并且不要忘记分配name
。
在这种情况下,
您真的不必重载operator=
因为默认生成的一个可以正常工作(通过依次分配每个成员和基类(。
运算符,就像调用另一个基类函数一样
std::vector<unsigned int>::operator=(rhv);
并让向量处理自己的赋值。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- C++尝试深度复制唯一指针时出现内存访问冲突
- 在 c++ 中使用深度复制的运算符重载
- 如何深度复制链表对象指针
- 我有两棵二叉树.我想在不更改输入树的情况下深度复制两个二叉树的结果
- 如何将结构深度复制到向量的每个元素
- 我需要做一个深度复制,我是否正确使用了我的复制构造函数?
- 是否可以在不显式迭代每个元素的情况下深度复制指针容器?
- 如何深度复制unique_ptr向量
- 二叉搜索树 深度复制和取消引用
- 是否有 pybind11::array_t 的(深度)复制构造函数
- 链表的这个别名运算符是否会产生深度复制
- 有没有一种 stl 方法来执行指针向量的深度复制
- cv::P oint3f 赋值运算符是否执行"深度"复制?
- Qt:通过深度复制访问列表中的数据结构是否应该比通过指针访问它慢得多
- 深度复制包含引用成员(C++)的结构
- 如何将“char *”深度复制到std::stringstream
- 如何在双向链表上执行深度复制
- 在复制构造函数中执行深度复制
- 深度复制cv::垫子替代品,哪个更好?