Home > Back-end >  How copy initialization works in the case of argument passing to a function?
How copy initialization works in the case of argument passing to a function?

Time:05-11

I googled about copy initialization and found out that whenever we write T a = b; ,copy initialisation takes place. It was also mentioned that copy initialization also takes when we pass arguments by value in a function call.

I wanted to know that whenever we pass arguments to a function, is the " = " operator used by the compiler to copy initialize the parameters of the function? I know that "=" is not needed in syntax of the function call but does the copy initialization itself use "=" during function call by value?

For example , In the code given below :

#include<iostream>
using namespace std;
void fun(T1 x, T2 y){
    // some code
}
int main(){
   T1 a;
   T2 b;
   solve(a,b);
}

Does initialization of parameters take place as T1 x = a ; and T2 y = b ; ? Is the "=" operator involved during the copy initialization of parameters in the function?

CodePudding user response:

Argument passing to the parameter of a function happens using copy initialization which is different than using copy assignment operator=. Note that initialization and assignment are two different things in C . In particular, passing argument happens using "copy initialization" and not "copy assignment".

From decl.init.general#14:

The initialization that occurs in the = form of a brace-or-equal-initializer or condition ([stmt.select]), as well as in argument passing, function return, throwing an exception ([except.throw]), handling an exception ([except.handle]), and aggregate member initialization ([dcl.init.aggr]), is called copy-initialization.

(end quote)

Similarly, from copy initialization:

Copy initialization is performed in the following situations:

    1. when passing an argument to a function by value

(end quote)

Also, note that the order of the copy initialization of the parameter from the arguments is unspecified.


Does initialization of parameters take place as T1 x = a ; and T2 y = b ; ?

In your example, when you passed arguments a and b to parameters x and y, the observed behavior would be as if we wrote T1 x = a; and T2 y = b;. You can verify this using this demo. Note again that the order of copy is unspecified.

CodePudding user response:

In initializing the function parameters, T1::operator= is not called. Instead T1::T1( const T1 &) is called.

The operator= could only be called if the argument were first constructed, using T1::T1(), which might not even exist.

You could create all these functions and put log-output in them to see this behavior in action.

  •  Tags:  
  • c
  • Related