Ishank Sharma
Ishank Sharma

Reputation: 99

What is { } when passed to a function in CPP?

The map insert function takes {string,int} as argument. how does this work?

#include <map>

using namespace std;

int main(int argc, char *arg[])
{
    map<string, int> m;

    m.insert({"a", 1});
}

Upvotes: 1

Views: 68

Answers (1)

songyuanyao
songyuanyao

Reputation: 172864

{"a", 1} is a braced-init-list, and when being passed to a function, copy-list-initialization (introduced in C++11) is performed.

function( { arg1, arg2, ... } )   (7)

7) in a function call expression, with braced-init-list used as an argument and list-initialization initializes the function parameter

Given map<string, int> m; and m.insert({"a", 1});, std::map::insert expectes a std::pair<const string, int>; therefore {"a", 1} is used to initialize a temporary std::pair which is passed to .insert(). The temporary std::pair is initialized by its constructor; initializing its members first to "a" and second to 1.

Upvotes: 3

Related Questions