这个赋值运算符重载会出现什么问题
当我的程序尝试将一个对象分配给另一个对象时,它崩溃了,你们看到这有什么问题吗?
变量为:
Field *fields[50];
int numOfFields;
int currentField;
函数为:
Screen& operator=(Screen &scr) {
if (this != &scr){
for (int i = 0; i < 50; i++)
fields[i] = NULL;
for (int i = 0; i < scr.numOfFields; i++)
fields[i] = scr.fields[i];
numOfFields = scr.numOfFields;
currentField = scr.currentField;
}
return *this;
}
My program crashes when it tries to assign one object to the other, do you guy see anything wrong with this?
The variables are:
Field *fields[50];
int numOfFields;
int currentField;
The function is:
Screen& operator=(Screen &scr) {
if (this != &scr){
for (int i = 0; i < 50; i++)
fields[i] = NULL;
for (int i = 0; i < scr.numOfFields; i++)
fields[i] = scr.fields[i];
numOfFields = scr.numOfFields;
currentField = scr.currentField;
}
return *this;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个问题可能是 scr.numOfFields 超过了目标对象中的字段数。
另一个问题是,或者至少看起来,您正在将指针分配给新对象。这意味着您将在程序中两次引用同一位置。如果它在一处被删除而另一处不知道会发生什么?当您尝试访问内存时,您会遇到段错误。
如果您有 Boost,您可以使用它们的共享指针来帮助避免这种情况: http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/smart_ptr.htm
One problem might be that scr.numOfFields exceeds the number of fields in your destination object.
Another problem is that, or at least it seems, you are assigning pointers to your new object. This means you will have a reference to the same location twice in the program. What happens if it gets deleted in one spot and the other doesn't know about it? When you try to access the memory you'll get a seg fault.
If you have Boost you can use their shared pointers to help avoid this : http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/smart_ptr.htm
您应该使用
std::vector
而不是动态数组,我怀疑您的问题很快就会消失。正如 MadCap 所建议的,您还应该使用共享指针,因为这是在容器中使用指针时的最佳实践。这也将为您提供您期望的复制语义。
这将消除对 this: 的需求,
并且您可以用 std::copy 替换 this:
,例如:
通过这样做,您将消除由于某些指针访问或初始化错误而发生崩溃的可能性。
简单的建议是;停止使用动态数组和原始指针并开始使用 std::vector 和 boost::shared_ptr ,而不是这样做将有助于防止您遇到此类问题。
You should use a
std::vector
instead of your dynamic array and I suspect your problem will go away very quickly.As suggested by MadCap you should also use shared pointers as this is best practice when using pointers with a container. Also this will give you the copy semantics that you expect.
This would negate the need for this:
and you could replace this:
with a std::copy, something like:
By doing this you will remove the possibility that the crash is occurring because of some pointer access or initialisation error.
Simple advice is; stop using dynamic arrays and raw pointers and start using
std::vector
andboost::shared_ptr
instead doing this will help to prevent you from running into these sorts of problems.