4

on a function call in c++, arguments are copied to the corresponding parameter. Is this initialization or assignment?

nbbk
  • 1,102
  • 2
  • 14
  • 32

3 Answers3

7

Argument passing semantics are that of initialization. Meaning, your classes' copy/move constructors will be invoked.

  • Not always a copy constructor is called. `myfunc(MyClass(3))` will invoke only the MyClass(int) constructor. – André Puel Feb 06 '13 at 20:18
  • You're (almost always) right. That's actually a compiler optimization, I believe, although almost all of them will actually do it ;) –  Feb 06 '13 at 20:21
  • g++ -O0 still does this "optimization". – André Puel Feb 06 '13 at 20:22
  • 1
    I only meant the compiler will do it because it's actually silly to create the temporary and then invoke the copy constructor to create another object. I'm not entirely sure the language's standard requires the implementation to do that, though. Be that as it may, you're right, not always will the copy constructor be invoked... –  Feb 06 '13 at 20:25
1

Then the arguments are by value they are copy-constructed (i.e. initialization).

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
0

Initialization: (please check the original-draft)

5.2.2 Function call

When a function is called, each parameter shall be initialized with its corresponding argument. [Such initializations are indeterminately sequenced with respect to each other] When a function is called, the parameters that have object type shall have completely-defined object type. [this still allows a parameter to be a pointer or reference to an incomplete class type. However, it prevents a passed-by-value parameter to have an incomplete class type.] During the initialization of a parameter, an implementation may avoid the construction of extra temporaries by combining the conversions on the associated argument and/or the construction of temporaries with the initialization of the parameter. The lifetime of a parameter ends when the function in which it is defined returns. The initialization and destruction of each parameter occurs within the context of the calling function. [the access of the constructor, conversion functions or destructor is checked at the point of call in the calling function. If a constructor or destructor for a function parameter throws an exception, the search for a handler starts in the scope of the calling function; in particular, if the function called has a function-try-block with a handler that could handle the exception, this handler is not considered.]

Community
  • 1
  • 1
qPCR4vir
  • 3,521
  • 1
  • 22
  • 32