Why would a copy constructor have more than one parameter?

后端 未结 4 950
闹比i
闹比i 2021-02-05 17:01

$12.8/2 - \'A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const

4条回答
  •  星月不相逢
    2021-02-05 17:21

    I have a situation where I require the copy constructor to have more than one parameter in one of my class involving deep copy.

    Basically the problem is that an object contains another object that need to keep track of it through a pointer, but a normal deep copy would only copy the pointer value and not the correct memory location of the new object.

    By disabling the normal copy constructor and using the variant with two parameters I'm able to deep copy correctly my object.

    [Edit]: looking through my code it seems that it is even more common than I though as I use it at a couple of place elsewhere too.

    Here is a code sample for the curious (this is a simplified version and is actually a little more complicated)

    //----------------------------------------------------------------------------- 
    scan_point::scan_point(scan_point const& rhs, simulation* sim_)
    : m(rhs.m), sim(sim_)
    //----------------------------------------------------------------------------- 
    {    
    
    }
    

    --

    simulation_(simulation_ const& rhs)
    {
        //...
        for(typename ContainerType::const_iterator it = rhs.spContainer->begin(), endIt = rhs.spContainer->end();
            it != endIt; it++)
        {
            spContainer->push_back(new scan_point(*it, this));
        }
    }
    

    --

    To makes things less painful during copy I use smart_ptr class that allow deep copy and (in this case specifically) embed my members in a struct to makes the compiler auto-generate the copying for about all other members (see for a try to a short example: https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-utility/1609496#1609496).

提交回复
热议问题