如何通过 std::vector 子类的重载赋值运算符进行深度复制<T>?

How to do deep copy by overloaded assignment operator of subclass of std::vector<T>?

本文关键字:复制 深度 lt gt vector std 何通过 子类 赋值运算符 重载      更新时间:2023-10-16

我有一个从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);

并让向量处理自己的赋值。