Does the compiler create the generated constructor / copy assignment its parameter with constant / volatile

There are some functions that the compiler can implicitly define for us if necessary and if they can be correctly defined for this class. how

  • default constructor
  • copy constructor
  • assignment operator
  • destructor.

So, no matter, the compiler-generated copy constructor / assignment takes its argument as const-reference

OR non-const-reference

.

class Test
{
  public:
    Test(const Test&);      << _1
    Test(Test&);            << _2 
};

      

If so, what are the driving factors for this decision.

+3


source to share


1 answer


The rules in the Pradhan link provided in the comments can be intuitively understood as follows: the compiler will try to define a copy constructor with an argument const T&

if possible ; if not, try defining a copy constructor with an argument T&

; and if this is not possible, then the copy constructor will be defined as remote.

When copying an object of a class type, T

its base classes and non-static data members must also be copied. So if one of them, say, U

has a copy constructor that accepts U&

instead const U&

, then it doesn't work if the constructor T

accepts const T&

, since all subobjects will then be cv-qual too, and you can't get U&

. Hence, the compiler should refuse to create a copy constructor that takes in const T&

, and instead goes with T&

. Likewise, if some base class or non-static data item cannot be copied, then it makes sense for the compiler to generate a remote copy instance for T

.



For copy assignment operators, the rules are basically the same, except that the compiler looks for copy assignment operators of base classes and non-static data members (rather than their copy constructors), and copy assignment operators can take their arguments by value (unlike copy constructors) ...

+1


source







All Articles