1

저는 파생 클래스를 2 개 가지고 파생 클래스를 가리키며 파생 객체를 가리키는 기본 포인터의 컨테이너가있는 entitymanager 클래스를가집니다. 나는 파생 클래스에서 복사 생성자를 돌볼 수있는 기반의 가상 복제 메서드를 가지고 있지만 할당 연산자를 오버로드하고 조각을 막을 때 머리를 감싸는 데 어려움을 겪고 있습니다. 누군가 도와 주면 어쩌면 어떻게 처리하는지 검토 할 수 있습니다. entitymanager 복사 생성자?오버로드 할당 연산자 - 다형성 컨테이너

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

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

할당 연산자의 인수는 '당신을 복사 생성자를 사용하여 복사 할 것입니다 : 나는 그것의 확인을

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; 
} 
+0

발생하는 특정 버그/문제가 있습니까? 이것이 단지 코드 검토 질문 일 경우 http://codereview.stackexchange.com에서보다 적합 할 것입니다. –

+0

내 특정 문제는 내가 다형 컨테이너 주어진 할당 연산자를 오버로드하는 방법을 알아야합니다. –

+0

@coolmrcroc 슬라이싱이 발생할 수 있다고 생각하는 구체적인 예를 제공 할 수 있습니까? – dasblinkenlight

답변

3

다음 복사 및 스왑 등의 과제를 구현하고, 용기를 스왑 swap 구성원 추가 생각 이미 쓰여진 경우 데이터를 스왑하므로 *this에 속한 데이터는 해당 매개 변수가 범위를 벗어날 때 삭제되고 *this은 새로 복사 된 데이터를 소유합니다.

이 방법으로 복사 생성자를 재사용한다는 것은 올바른 복사 생성자 (올바른 스왑은 일반적으로 쉽게 얻을 수 있음)를 구현하기 만하면 할당 연산자가 실제로 간단하고 자동으로 정확하다는 것을 의미합니다.

N.B. 귀하의 init 회원 및 사본 ctor 예외 안전하지 않습니다, 어떤 push_back 작업 예외가 발생하면 메모리 누수. 소멸자도 누락되었습니다. 그러나 실제 코드에 존재한다고 가정합니다.

+0

+1, 할 수있을 때마다 항상'swap'을 구현해야합니다 (또한 무료 함수 인 swap을 제공해야합니다). 이는 코드 단순화 및 예외 보장 제공에 도움이됩니다. –