指向包含vector <int> issue </int>的实例类的指针

时间:2011-04-16 10:59:39

标签: c++ pointers vector copy bigint

我有一个这样的课程:

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);

}

我认为我缺少/不管理矢量设计中的某些东西.. 我可以实现指针的无副本分配,即使没有实现新的bigInt吗? 谢谢专家!

1 个答案:

答案 0 :(得分: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