0

我有这样的课:

class largeInt{
  vector<int> myVector;
  largeInt  operator*  (const largeInt &arg);

}

在我的主要工作中,我在使用指针时无法避免复制:

void main(){

    //this works but there are multiple copies: I return a copy of the calculated
    //largeInt from the multiplication and then i create a new largeInt from that copy.
    largeInt testNum = 10;
    largeInt *pNum = new HugeInt( testNum*10);

    //i think this code avoid one copy but at the end hI points to a largeInt that has
    // myVector = 0 (seems to be a new instance = 0 ). With simple ints this works  great.
    largeInt i = 10;
    largeInt *hI;
    hI = &(i*10);

}

我想我在矢量设计中缺少/没有管理一些东西。即使没有实例化一个新的 largeInt,我可以实现指针的无副本分配吗?谢谢各位专家!

4

1 回答 1

1

hI = &(i*10);获取一个临时largeInt 的地址,该地址在 ';' 之后立即被破坏 - 所以hI指向无效内存。

当你将两个相乘时,largeInt得到一个新实例——这就是乘法的作用。也许你打算做一个operator*=?那应该修改现有实例而不是创建新实例。

考虑:

int L = 3, R = 5;

int j = L*R; // You *want* a new instance - L and R shouldn't change
L*=R; // You don't want a new instance - L is modified, R is unchanged

此外,您不应该使用new在堆上创建 largeInt - 只需这样做:

largeInt i = 10; 
largeInt hi = i*10; // Create a temporary, copy construct from the temporary

或者:

largeInt i = 10;
largeInt hi = i; // Copy construction
hi *= 10; // Modify hi directly
于 2011-04-16T11:04:21.857 回答