Reputation: 161
In C++17 code, I sometimes see something like:
void myfunction(const std::string& arg1, int arg2) {
//...
}
void otherfunction() {
myfunction("a",1);
myfunction({},2);
myfunction("b",{});
myfunction({},{});
}
What do the empty curly brace arguments means?
I found that I get an empty string and 0 integer, so I suppose it's some kind of default value.
Upvotes: 3
Views: 2429
Reputation: 11028
This was introduced in C++17 and is called list-initialization.
When the braces are empty, it will perform value initialization:
For scalar types such as int
, it will be as if you define it in global scope, i.e it will be zero-initialized (also true for class instances with default constructor that is not user-provided and not deleted, unless it has a non-trivial default constructor in which case it will be default initialized).
If class type with no default constructor or if the default constructor has been marked deleted, it will perform default initialization (ex. T t;
), this is also true if there is a user defined constructor.
Examples:
struct A {
A() : x{1}, y{2} {}
int x,y;
};
/* A has a default user-provided constructor,
* calls default constructor */
A a{};
//////////////////////////
struct B {
B() {}
int x, y;
string z;
};
/* B has a user defined default constructor,
* since x and y are not mentioned in the initializer list,
* B::x and B::y contain intermediate values,
* while, B::z will be default initialized to "" */
B b{};
//////////////////////////
struct C {
int x, y;
};
/* C has an implicit default constructor,
* C::x and C::y will be zero-initialized */
C c{};
//////////////////////////
Upvotes: 4