Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ what does standalone curly bracket mean in function parameter?

Tags:

c++

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?

like image 301
Catiger3331 Avatar asked Mar 01 '26 03:03

Catiger3331


1 Answers

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
like image 172
Dhwani Katagade Avatar answered Mar 03 '26 15:03

Dhwani Katagade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!