lundi 28 mai 2018

Usage of this* in make_unique

I have a small example of Factory design pattern, and I am interested in this part std::make_unique< A >(*this) especially *this. Does it mean that the clone() method return unique pointer which point to member of factory class? And createInstance() returns always the same member of Factory class? I am just confused what std::make_unique< A >(*this) is supposed to do, because A has in constructor std::string, not a pointer to itself.

Example:

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

class A: public Base{
        std::string name_;
    public:
        A(std::string name ){name_ = name;};
        std::unique_ptr<Base> clone() override{
            return std::make_unique<A>(*this);
        };
        void print( ) override{
            std::cout << "Class A: " << name_;    
        };
        virtual ~A(){};
};

class Factory{
        std::unique_ptr<A> type = std::make_unique<A>("MyName");  
    public:
        std::unique_ptr<Base> createInstance(){
            return type->clone();
    }
};

int main(){
    Factory factory;
    auto instance = factory.createInstance();
    instance->print();
}

Aucun commentaire:

Enregistrer un commentaire