What's the best signature for clone() in C++?

后端 未结 8 1463
别那么骄傲
别那么骄傲 2020-12-05 10:41

As Scott Myers wrote, you can take advantage of a relaxation in C++\'s type-system to declare clone() to return a pointer to the actual type being declared:

         


        
8条回答
  •  天命终不由人
    2020-12-05 11:06

    Use the Public non-virtual / Private virtual pattern :

    class Base {
        public:
        std::auto_ptr clone () { return doClone(); }
        private:
        virtual Base* doClone() { return new (*this); }
    };
    class Derived : public Base {
        public:
        std::auto_ptr clone () { return doClone(); }
        private:
        virtual Derived* doClone() { return new (*this); }
    };
    

提交回复
热议问题