How can I extend a compiler generated copy constructor

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

    I'd say create a smart pointer that handles the copying, and then use it as a member of your class. These codes may give you an idea:

    Depending on how the base call constructor is initiated, the member's constructors will be called the same way. For example, let's start with:

    struct ABC{
        int a;
        ABC() : a(0)    {   printf("Default Constructor Called %d\n", a);   };
    
        ABC(ABC  & other )  
        {
            a=other.a;
            printf("Copy constructor Called %d \n" , a ) ;
        };
    };
    
    struct ABCDaddy{
        ABC abcchild;
    };
    

    You can do these tests:

    printf("\n\nTest two, where ABC is a member of another structure\n" );
    ABCDaddy aD;
    aD.abcchild.a=2;
    
    printf( "\n Test: ABCDaddy bD=aD;  \n" );
    ABCDaddy bD=aD; // Does call the copy constructor of the members of the structure ABCDaddy ( ie. the copy constructor of ABC is  called)
    
    printf( "\n Test: ABCDaddy cD(aD); \n" );
    ABCDaddy cD(aD);    // Does call the copy constructor of the members of the structure ABCDaddy ( ie. the copy constructor of ABC is  called)
    
    printf( "\n Test: ABCDaddy eD; eD=aD;  \n" );
    ABCDaddy eD;
    eD=aD;          // Does NOT call the copy constructor of the members of the structure ABCDaddy ( ie. the copy constructor of ABC is not called)
    

    Output:

    Default Constructor Called 0
    
    Test: ABCDaddy bD=aD;
    Copy constructor Called 2
    
    Test: ABCDaddy cD(aD);
    Copy constructor Called 2
    
    Test: ABCDaddy eD; eD=aD;
    Default Constructor Called 0
    

    Enjoy.

提交回复
热议问题