简体   繁体   中英

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 0xFFFFFFFFFFFFFFFF.

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
    {
    private:
        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

public:
    XMLObjects(){}
    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; }
    ~XMLObjects(){}

    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;
objects.push_front(obj1);
objects.push_front(obj2);
objects.push_front(obj3);
list<XMLObjects> NewObjectsList;
std::copy(objects.begin(), objects.end(), NewObjectsList.begin());

Can anyone help?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM