指向包含向量的实例类的指针问题
我有一个这样的类:
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吗? 谢谢各位专家!
I have a class like this:
class largeInt{
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
hI = &(i*10);
获取一个临时 largeInt 的地址,该地址在“;”之后立即被破坏- 所以hI
指向无效内存。当您将两个
largeInt
相乘时,您确实会得到一个新实例 - 这就是乘法的作用。也许您打算创建一个operator*=
来代替?这应该修改现有实例而不是创建新实例。考虑:
此外,您不应该使用
new
在堆上创建 largeInt - 只需这样做:或者:
hI = &(i*10);
takes the address of a temporary largeInt which is destructed immediately after the ';' - sohI
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 anoperator*=
instead? That should modify an existing instance rather than creating a new.Consider:
Also, you shouldn't use
new
to create largeInt's on heap - just do like this:Or: