How can I extend a compiler generated copy constructor

后端 未结 5 815
梦如初夏
梦如初夏 2020-12-17 09:41

I frequently run into the problem, that I must extend a compiler generated copy constructor. Example:

class xyz;
class C
{
    ...
    int a, b, c; 
    std:         


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-17 10:18

    You might place your special member in a base class, something like:

    class xyz;
    
    class SpecialCopyXYZ
    {
    public:
        SpecialCopyXYZ() = default;
        SpecialCopyXYZ(const SpecialCopyXYZ& rhs)
        {
           if (CanCopy(other.some_private_ptr)) {
              some_private_ptr = other.some_private_ptr;
           } else {
              some_private_ptr = nullptr;
           }
        }
    
        // SpecialCopyXYZ& operator=(const SpecialCopyXYZ& rhs)
    
    protected:
        xyz *some_private_ptr = nullptr;
    };
    
    
    class C : private SpecialCopyXYZ
    {
    public:
        C(const C &other) = default;
    private:
        int a, b, c; 
        std::set mySet;
    };
    

    If SpecialCopyXYZ need C data, you may use CRTP and downcast.

提交回复
热议问题