代码之家  ›  专栏  ›  技术社区  ›  Martijn Courteaux

C++:关于复制构造函数的问题

  •  2
  • Martijn Courteaux  · 技术社区  · 15 年前

    this void* 指针。但问题是,当我传递该类的一个实例时 按价值 ,指针将不会更改为堆栈上的新地址。所以,我想重写copy构造函数,用

    我希望我解释得很好。。。

    所以问题是:我是否可以保留默认复制构造函数的过程,在这里我添加了重新分配指针的部分?还是有更好的选择?

    谢谢

    下面是一些代码:

    class GetsCopiedByValue : public SuperClass
    {
        GetsCopiedByValue(Type1 *t1, Type2 *t2, float var1, /* A lot of other things I need */) :
             SuperClass(t1, t2), var1(var1)
        {
             t1->set_GetsCopiedByValue_Address(this);  // ***
        }
    }
    

    其他地方:

    {
        GetsCopiedByValue instance (t1, t2, 4.64, /* All the other things */);
        SomeType *t = new SomeType(instance); // <-- here, it gets copied by value,
    }  // but the original "instance" goes (here) out of scope and the address 
       // I assigned (***) is not longer valid, so I have to
       // reassign the address to the new address, after copying it.
    
    2 回复  |  直到 15 年前
        1
  •  2
  •   Konrad Rudolph    15 年前

    不确定这是否有用,但你 可以 实际调用复制构造函数中的超类复制构造函数:

    GetsCopiedByValue(GetsCopiedByValue const& other) :
         SuperClass(other), var1(other.var1)
    {
         t1->set_GetsCopiedByValue_Address(this);
    }
    

    但我认为即使省略了基类构造函数调用,C++也会为您插入它。

        2
  •  0
  •   Community CDub    8 年前

    当您首先构造一个对象(可能是在超类中,因为这就是使用它们的原因)然后在复制构造中再次使用它们(即从您要复制的对象中读出它们)时,您必须存储掉这些参数。

    编辑

    更好的办法是,像@Konrad rudolph那样做 suggests