How can I extend a compiler generated copy constructor

后端 未结 5 818
梦如初夏
梦如初夏 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:06

    The easiest way is to introduce a base class:

    class xyz;
    
    struct CDetail {
      //...
      int a, b, c; 
      std::set mySet;
      xyz *some_private_ptr;
    };
    
    struct C : private CDetail {
      C(C const &other)
      : CDetail(other)
      {
        if (!CanCopy(other.some_private_ptr))
          some_private_ptr = 0;
        // opposite case already handled
      }
    };
    

    This is an abuse of inheritance to an extent, but the advantages over a nested "impl" class are 1) you can access each member as "name" rather than "data.name" (reducing code changes when refactoring), and 2) (though only sometimes desired) you can "promote" individual members to protected or public without affecting other members:

    struct C : private CDetail {
    protected:
      using CDetail::a;
    };
    
    struct D : C {
      void f() {
        cout << a;
      }
    };
    
    int main() {
      D d;
      d.f();  // D can access 'a'
      cout << d.a;  // main cannot access 'a'
      return 0;
    }
    

提交回复
热议问题