Search code examples
c++returnlist-initialization

Meaning of `{}` for return expression


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?


Solution

  • 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: