2

我有一个this用来初始化void*指针的类。但问题是,当我通过value传递该类的实例时,指针不会更改为堆栈上的新地址。所以,我想重写复制构造函数以重新分配具有新地址的指针this。但是我需要变量来调用超类构造函数,我通常通过构造函数参数获得,但我的复制构造函数中没有它们......

希望我解释清楚...

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

谢谢

这是一些代码:

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.
4

2 回答 2

2

不确定这是否有帮助,但您实际上可以在复制构造函数中调用超类复制构造函数:

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

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

于 2010-08-07T15:43:07.533 回答
0

当您第一次构造对象时(可能在超类中,因为这就是使用它们的对象),您必须存储参数,然后在复制构造中再次使用它们,即从您正在复制的对象中读取它们。

编辑

更好的是,按照@Konrad Rudoplh 的建议,为基类定义和使用复制构造函数。

于 2010-08-07T15:35:31.210 回答