What would the problem be with this assignment operator overload
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& op开发者_JAVA技巧erator=(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;
}
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
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:
for (int i = 0; i < 50; i++)
fields[i] = NULL;
and you could replace this:
for (int i = 0; i < scr.numOfFields; i++)
fields[i] = scr.fields[i];
with a std::copy, something like:
fields.clear()
std::copy(scr.fields.begin(), scr.fields.end(), fields.begin());
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
and boost::shared_ptr
instead doing this will help to prevent you from running into these sorts of problems.
精彩评论