For example, consider the following code:
class C{};
void foo(C c){}
foo({});
Will the compiler default initialize a variable of type C and pass it to the function parameter?
Expanding the example in the question a bit, adding copy, move and initializer_list constructors.
#include <iostream>
using namespace std;
class C{
public:
C() { cout << "default ctor" << endl; }
C(const C&) { cout << "copy ctor" << endl; }
C(C&&) { cout << "move ctor" << endl; }
C(initializer_list<int>) { cout << "initializer_list ctor" << endl; }
};
void foo(C c) { cout << "in foo" << endl; }
int main()
{
foo({});
return 0;
}
The above run with g++ -std=c++14 -fno-elide-constructors main.cpp && ./a.out gives the following output.
default ctor
in foo
So yes, it does directly default construct the formal parameter for function foo, pretty much ignoring the initializer_list.
However, for a slight change like this foo({1}) it does call the initializer_list constructor.
initializer_list ctor
in foo
For a change like this foo(C{}) it first calls the default constructor and then moves it to the formal parameter.
default ctor
move ctor
in foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With