Why would a copy constructor have more than one parameter?

后端 未结 4 954
闹比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:11

    Very cool. Looks like a good way to pass hints to the copy constructor. Some example situations I can think of where this might be useful:

    • Copying a data structure where the copy will then be populated with additional data

      The additional parameter would hint at the likely soon -to-be-needed capacity to optimize allocation. The default capacity would be a sentinel value to indicate just use the default capacity or the capacity of the original data structure.

    • Whether to do a deep copy or shallow copy of member values

      The default might be to do a deep copy for safety, but advanced uses could take advantage of specifying rare occasions of when its safe to do a shallow copy.

    • Verbatim copy vs logical copy

      Hint whether the data structure's copy constructor should copy the original data structure's internal structure verbatim or whether its safe to optimize or consolidate it. For example, the hint could indicate a tree should be balanced as it is copied.

提交回复
热议问题