pointer to instance class containing vector<int> issue
I have a class like this:
class lar开发者_运维技巧geInt{
vector<int> myVector;
largeInt operator* (const largeInt &arg);
}
in my main i can't avoid copies while working with pointers:
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);
}
I think I'm missing/not managing something in vector design.. I could i achieve a copyless assigment of a pointer, even without instanciating a new largeInt? Thank you experts!
hI = &(i*10);
takes the address of a temporary largeInt which is destructed immediately after the ';' - so hI
points to invalid memory.
When you multiply two largeInt
you do get a new instance - that's what multiplication does. Perhaps you intended to make an operator*=
instead? That should modify an existing instance rather than creating a new.
Consider:
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
Also, you shouldn't use new
to create largeInt's on heap - just do like this:
largeInt i = 10;
largeInt hi = i*10; // Create a temporary, copy construct from the temporary
Or:
largeInt i = 10;
largeInt hi = i; // Copy construction
hi *= 10; // Modify hi directly
精彩评论