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、無効なメモリを指します。

largeInt2を掛けると、新しいインスタンスが得られます。これが掛け算の役割です。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 に答える