Meaning of `{}` for return expression

Viewed 2318

I found by accident that the following compiles:

#include <string>
#include <iostream>

class A{
    int i{};
    std::string s{};
    public:
        A(int _i, const std::string& _s) : i(_i), s(_s) {
            puts("Called A(int, const std::string)");
        }

};

A foo(int k, const char* cstr){
    return {k, cstr};           // (*)
}

int main(){
    auto a = foo(10, "Hi!");
    return 0;
}

The line of interest is (*). I guess the function foo is equivalent to:

A foo(int k, const char* str){
    return A(k, cstr);
}

However, is there a special name for this mechanism in (*)? Or is it just the simple fact that the compiler knows which constructor to call due to the return type?

2 Answers

return {k, cstr}; means that {k, cstr} is the initializer for the return value. Also, it indicates "return an object of the function's return type initialized with k and cstr, which means that the exact behavior depends on the returned object's type".

The return value can be initialized in two different ways:

This is a specific form of copy list initialization

See number 8 on the list in that reference:

List initialization is performed in the following situations:

...

copy-list-initialization (both explicit and non-explicit constructors are considered, but only non-explicit constructors may be called)

...

  1. in a return statement with braced-init-list used as the return expression and list-initialization initializes the returned object
Related