[英]pointer to instance class containing vector<int> 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
相乘時,您會得到一個新實例-這就是乘法的作用。 也許您打算改成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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.