STF STF - 1 year ago 175
C++ Question

C++: std::copy fails with access violation reading location error

I'm trying to copy a list of objects from class that was created by me using the std::copy C++ function, but the function crashes with the next error message:

Unhandled exception at 0x00007FFA91BAC570 (msvcr120.dll) in
MyProject.exe: 0xC0000005: Access violation reading location

The class is pretty simple and I have no idea what can cause the copy function to crash with such error.
The class looks as follow:

class XMLObjects
int id;
string name;
int leftUpCornerX;
int leftUpCornerY;
int rightDownCornerX;
int rightDownCornerY;
bool isFound; //it's true if this object was found in the OR file and in the GT file

XMLObjects(int _id){ id = _id; }
XMLObjects(int _id, string _name, int _leftUpCornerX, int _leftUpCornerY, int _rightDownCornerX, int _rightDownCornerY) { id = _id; name = _name; leftUpCornerX = _leftUpCornerX; leftUpCornerY = _leftUpCornerY; rightDownCornerX = _rightDownCornerX; rightDownCornerY = _rightDownCornerY; isFound = false; }

void setID(int _id){ id = _id; }
void setName( string _name){ name=_name; }
void setLeftUpCorner(int _leftUpCornerX, int _leftUpCornerY){ leftUpCornerX = _leftUpCornerX; leftUpCornerY = _leftUpCornerY; }
void setRightDownCorner(int _rightDownCornerX, int _rightDownCornerY){ rightDownCornerX = _rightDownCornerX; rightDownCornerY = _rightDownCornerY; }
void objectWasFound(){ isFound = true; }

int getID(){ return id; }
string getName(){ return name; }
int getLeftUpCornerX(){ return leftUpCornerX; }
int getLeftUpCornerY(){ return leftUpCornerY; }
int getRightDownCornerX(){ return rightDownCornerX; }
int getRightDownCornerY(){ return rightDownCornerY; }
bool isObjectFound(){ return isFound; }

The call to the copy function looks as follow:

list<XMLObjects> objects;
list<XMLObjects> NewObjectsList;
std::copy(objects.begin(), objects.end(), NewObjectsList.begin());

Can anyone help?

Answer Source

std::copy doesn't resize output, so you have to resize your container before or use special iterator which insert element.

You may use following code.

std::copy(objects.begin(), objects.end(),
          std::inserter(NewObjectsList, NewObjectsList.end()));

As noted in comment, in your case, you may directly do a copy:

list<XMLObjects> NewObjectsList = objects;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download