虚拟赋值运算符不允许static_cast

时间:2016-06-01 19:16:34

标签: c++ polymorphism assignment-operator

我有以下MWE代码:

#include <algorithm>

class Base{
public:
    int baseMember;
    friend void swap(Base& in, Base& out)
    {
        using std::swap;
        swap(in.baseMember, out.baseMember);
    }
    virtual Base& operator=(Base obj)
    {
        swap(*this, obj);
        return *this;
    }
    Base() : baseMember(1)
    {       
    }
};
class Derived : public Base
{
public:
    int derivedMember;
    friend void swap(Derived& in, Derived& out)
    {
        using std::swap;
        swap(in.derivedMember, out.derivedMember);
        swap(static_cast<Base&>(in), static_cast<Base&>(out));
    }
    virtual Base& operator=(Base obj)
    {
        swap(*this, static_cast<Derived&>(obj));
        return *this;
    }
    Derived() : Base(), derivedMember(2)
    {
    }
};

int main()
{
    Base *b1 = new Derived();
    Base *b2 = new Derived();
    *b1 = *b2;
    delete b1;
    delete b2;
}

我有两个Base指针指向Derived数据。然后我做了指针内容的分配。自Base班级&#39;赋值运算符为virtual,多态性启动,而Derived类的赋值运算符(具有相同的签名)则被调用。

但是,将源转换为static_cast对象的Derived失败。或者,它成功地将其转换为Derived对象,但其derivedMember是垃圾(在最初在构造函数中设置之后)。

如何避免这种情况?如何在两个Derived指针的Base内容之间进行分配?

2 个答案:

答案 0 :(得分:3)

您的代码存在拼写错误且本质上不安全的行为。错字在这里:

virtual Base& operator=(Base obj) // <-- should be base&
{
    swap(*this, static_cast<Derived&>(obj));
    return *this;
}

如果你解决了这个问题,你的代码应该在提供的简单示例中 。但它仍然会失败,因为您如何保证传递给operator=的参数实际上是Derived类型?

答案 1 :(得分:1)

通过值切片参数传递参数。因此,当您调用operator=函数时,您实际为Base,而不是Derived

我担心你需要为lvalues和rvalues重载你的作业。

virtual Base& operator=(const Base&);
virtual Base& operator=(Base&&);