C++ Smart pointer implementation for polymorphism without needing to maintain clonability – Why have I never heard of something like this before?

I recently needed to use a list of different derived classes, as one does quite often, and found myself in situation where I had already researched a ton (I know the principles but just wanted to see how people normally do it), but couldn’t find a single satisfying solution.

The problem goes as follows:
You want an object that can hold any derived class of a base class, so an owning base class pointer, though as a c++ programmer you do not want to deal with raw new and delete outside of their respective wrapper classes. You decide you’d use a smart pointer (mainly std::unique_ptr) like everyone suggests, but then find out that it is non copyable which is a functionality you also really need. std::shared_ptr instead is copyable, but you don’t want to duplicate just the base pointer, but the (derived) object it points to too (perform a deep copy). A new pointer to a new object in memory with the same values. What to do? After a lot of research you find out about the clone pattern, the use of something called CRTP, and some other (rather unconvenient) ways. Implementing a clone method in every base and derived class you may want to use seems kind of redundant, since it always does the same. Creating a new factory-like class for CRTP also seems kind of odd, since you know the type of the currently stored derived through the set method template (see code). You would just need to save it and cast the base pointer to whatever this template was at the point of setting your pointer in the copy constructor.

This brings me to the core question and as to why no one has brought up a simple and straight forward solution to this. I mean you just need to store a derived type of base dynamically, right? After some hours of further research and thinking myself, I think I found such a clean and simple solution, though I am not sure why no one proposed things like this anywhere or why I just could not find them no matter what I searched for. Are there any drawbacks to using this or is there anything I’ve missed? To me this seems like one of a few optimal ways of handling all this.

I basically just used a std::function which is dynamically overwritten whenever the pointer is set to a new derived to return a new object of the (just then) known derived type. For what I’ve tested it works perfectly fine and as expected, but what do you think of it? And have you found implementations somewhere or even have your own?

Here’s the implementation I have:
(Sure there are still some things to add like a direct assignment operator overload and stuff but for now it’s okay like this.)

template <typename BaseType>
class PolyPtr {
private:
    BaseType* basePtr;
    std::function<BaseType*()> cloneFunc;
    
public:
    PolyPtr() {
        basePtr = nullptr;
    }
    
    PolyPtr(const PolyPtr &pCopyFrom) {
        basePtr = pCopyFrom.cloneFunc();
    }
    
    ~PolyPtr() {
        clear();
    }
    
    BaseType* get() {
        return basePtr;
    }
    
    template <typename DerivedType>
    DerivedType* getDerived() {
        DerivedType* derivedPtr = dynamic_cast<DerivedType*>(basePtr);
        return (derivedPtr ? derivedPtr : nullptr);
    }
    
    template <typename DerivedType>
    void set(DerivedType pNewObject) {
        clear();
        basePtr = new DerivedType(pNewObject);
        cloneFunc = [basePtr = this->basePtr]() -> DerivedType* {return new DerivedType(*static_cast<DerivedType*>(basePtr));};
    }
    
    void clear() {
        delete basePtr;
        basePtr = nullptr;
        cloneFunc = []() -> BaseType* {return nullptr;};
    }
};

New contributor

UniCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật