vendredi 2 juin 2017

C++: vector assignment run-time error when defining copy-assignment and copy-constructor

I ran into this bug when i tried to re-assign to a vector of class objects, the program compiled fine, but when i tried to run it when a vector assigned twice the program crashed.

TVector<doorway> doorSet;
doorSet.assign({ doorway(0, "south"), doorway(3, "door") });
doorSet.assign({ doorway(2, "door"), doorway(3, "teleporter") });

//struct doorway
struct doorway
{

    doorway(): _ID(-1), _door("Empty"){}
    doorway(int ID, FText door): _ID( ID ), _door( door ) {}

    //copy assignment constructor
    doorway(const doorway& obj):
        _ID(obj._ID),
        _door(obj._door)
    {}


    //is this neccessary?
    friend void swap(doorway& first, doorway& second)
    {
        using std::swap;

        swap(first._ID, second._ID);
        swap(first._door, second._door);

    }

    doorway& operator=(doorway obj)
    {

        std::swap(*this, obj);

        return *this;
    }

    int32 _ID;
    FText _door;

};

note: sorry about the weird code layout, not used to this sites code notation

I noticed that it worked if I erased the vector before re-assigning it, and when I thought about it and I figured out that by explicitly defining the copy-constructor and copy-assignment operator that I was either implicitly deleting a constructor needed for vector assignment or I was not correctly defining the two : so I erased the functions and the code worked fine then.

I'm wondering what i did that caused my program to crash. did I not define the copy-constructor and copy-assignment operator correctly, or did i not explicitly define another function required for the vector assignment to work? thanks.

edit: sorry, but i just remembered that i am taking a udemy course, and am using weird types. FText is simply a string object and TVector is just a pre-processor directive replacement for vector

Aucun commentaire:

Enregistrer un commentaire