指向包含向量问题的实例类的指针<int>

pointer to instance class containing vector<int> issue

本文关键字:gt int lt 指针 实例 包含 向量 问题      更新时间:2023-10-16

我有一个这样的类:

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

在我的main中,我不能避免使用指针时的复制:

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得到一个新的实例-这就是乘法的作用。也许你打算做一个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