dimanche 13 janvier 2019

Implement the prototype design pattern in C++ without using the new operator

Is it possible to implement the prototype design pattern in C++ without using the new operator?

For instance, let us use the example from the SO

class BaseVirtualClass{
public:
    virtual int foo() = 0;
    virtual BaseVirtualClass * clone() = 0;
    virtual ~BaseVirtualClass(){}
};

class DerivedClass: public BaseVirtualClass{
    int state;
public:
    DerivedClass(int a):state(a){}
    DerivedClass( const DerivedClass & other)
        : state(other.state){}
    int foo(){ // override
        return state;
    }

    BaseVirtualClass * clone(){ //override
         // I'm using copy constructor here, but hidden from user
         return new DerivedClass(*this);
    }
};

So, in this line return new DerivedClass(*this); we are calling the constructor of the DerivedClass, while I would expect to perform some kind of operation which would literally take the memory of the object and copy that memory without calling a constructor. Is it possible in C++ or does everyone mean to call a copy constructor when he or she says something like this:

The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:

  • avoid subclasses of an object creator in the client application, like the factory method pattern does.
  • avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.

Aucun commentaire:

Enregistrer un commentaire