简体   繁体   中英

overloading assignment operator - polymorphic containers

i have a base class, 2 derived classes and an entitymanager class that has a container of base pointers pointing to derived objects. i have a virtual clone method in the base to take care of the copy constructors in the derived classes, but im having trouble wrapping my head around overloading the assignment operator and preventing slicing, could someone please help with that and perhaps review how ive handled the entitymanager copy constructor? i think its ok

class System
{
public:
    virtual System* clone()=0;
};

class projectile :public System
{
public:
    projectile* clone()
    {
        return new projectile(*this);
    }
};

class player : public System
{
public:
     player* clone()
    {
        return new player(*this);
    }
};

class EntityManager
{
private:
    vector<System*> theEntities;
public:
    EntityManager(){}
    EntityManager(EntityManager& other)
    {
        for (size_t i=0;i<other.theEntities.size();i++)
            theEntities.push_back(other.theEntities[i]->clone());
    }
    void init()
    {
        projectile* aProjectile = new projectile;
        player* aPlayer = new player;
        theEntities.push_back(aProjectile);
        theEntities.push_back(aPlayer);
    }
};

int main (int argc, char * const argv[]) 
{
    EntityManager originalManager;
    originalManager.init();
    EntityManager copyManager(originalManager);

    return 0;
}

Add a swap member that swaps the containers, then implement assignment as copy and swap:

void swap(EntityManager& other)
{ theEntities.swap(other.theEntities); }

EntityManager& operator=(EntityManager other)
{ swap(other); return *this; }

The argument to the assignment operator will be copied using the copy constructor you've already written, then you swap the data, so the data that belonged to *this will be destroyed when that parameter goes out of scope, and *this owns the newly copied data.

Re-using the copy constructor in this way means you only need to implement a correct copy constructor (and correct swap, which is usually easy to get right) and your assignment operator is really simple and automatically correct.

NB your init member and copy ctor are not exception safe, if any push_back operation throws an exception you leak memory. You're also missing a destructor, but I assume that's present in the real code.

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