2013-09-23 36 views
0

我需要複製一個向量的多態對象,在新的向量中應該有指向相同的多態類型的指針,而不是指向相同的數據,而是應該指向新的數據堆。該數據需要設置爲與原始矢量相同的數據。複製指針向量而不切片

std::vector < Component * > entity = baseEntity; 
在這種情況下,新矢量實體只是獲取指針從baseEntity

。這裏不會發生切片,但是當我更改baseEntity中的指針時,它也會更改實體中的數據。如何正確複製我的情況?

+0

「新矢量sho uld是指向相同的多態類型的指針,而不是指向相同的數據「 - 他們必須指向* something *。你想*複製對象或只是指針? – WhozCraig

+5

你必須讓你的'Component'對象[cloneable](http://stackoverflow.com/a/5148751/10077)。 –

+2

我會建議智能指針,而不是原始指針。 – chris

回答

1

這裏是克隆的例子:

#include <memory> 
#include <vector> 

struct Component { 
    virtual std::unique_ptr<Component> clone() const = 0; 
}; 

struct AComponent : Component { 
    virtual std::unique_ptr<Component> clone() const 
    { 
    return std::unique_ptr<Component>(new AComponent(*this)); 
    } 
}; 

struct BComponent : Component { 
    virtual std::unique_ptr<Component> clone() const 
    { 
    return std::unique_ptr<Component>(new BComponent(*this)); 
    } 
}; 

int main(int,char**) 
{ 
    std::vector<std::unique_ptr<Component>> old_entities; 
    old_entities.push_back(std::unique_ptr<Component>(new AComponent)); 
    old_entities.push_back(std::unique_ptr<Component>(new BComponent)); 
    std::vector<std::unique_ptr<Component>> new_entities; 
    new_entities.reserve(old_entities.size()); 
    for (auto &entity : old_entities) { 
    new_entities.push_back(entity->clone()); 
    } 
} 
1

爲了實現這一目標,你必須提供克隆在多態的方式對象的方法,那就是提供一個重寫的克隆功能:

class Base 
{ 
public: 
    virtual std::unique_ptr<Base> clone() = 0; 
}; 

class Foo : public Base 
{ 
    int _class_stuff; 

public: 
    virtual std::unique_ptr<Base> clone() 
    { 
     return std::unique_ptr(new Foo(*this)); //Calls copy ctor 
    } 
}; 

現在當複製矢量時,遍歷它調用每個元素的克隆方法:

std::vector<std::unique_ptr<Base>> clone_vector(const std::vector<std::unique_ptr<Base>>& vector) 
{ 
    std::vector<std::unique_ptr<Base>> result; 

    for(auto& element : vector) 
     result.push_back(element->clone()); 

    return result; 
}