c++c++11smart-pointersunique-ptrfactory-pattern

Usage of this* in make_unique


I have a small example of a 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 a std::unique_ptr which points to member of factory class? And createInstance() always returns the same member of the 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.

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();
}

Solution

  • std::make_unique<A>(*this) is basically equivalent to:

    unique_ptr<A>(new A(*this))
    

    In clone(), *this is an lvalue-reference to A, so you are constructing a A from an (lvalue-reference to) A (inside std::make_unique), so you are using the implicitly declared copy-constructor of A:

    A(A const&);
    

    So you are effectively making a copy of the current object into a newly allocate block of memory.

    Since createInstance uses clone(), you are creating a "copy" of type each time you call createInstance.