指向包含vector issue的实例类的指针

| 我有这样的课:
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,我也可以实现指针的无复制分配? 谢谢高手!     
已邀请:
hI = &(i*10);
占用一个临时largeInt的地址,该地址在\'; \'之后立即被破坏-因此
hI
指向无效的内存。 当您将两个
largeInt
相乘时,您会得到一个新实例-这就是乘法的作用。也许您打算改成ѭ5??那应该修改一个现有实例而不是创建一个新实例。 考虑:
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
    

要回复问题请先登录注册