Meaning of `{}` for return expression

15

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?

Share
Improve this question
5
  • 20
    It's known as copy list initialization, it's a convenient way to return stuff. – Nathan Pierson May 10 at 17:55
  • 2
    It could depend upon the particular C++ standard you refer to. See this C++ reference and read n3337 or some newer C++ standard. – Basile Starynkevitch May 10 at 17:55
  • Thanks to both of you. @NathanPierson Feel free to post your comment as an answer, so I can accept it. – Ronaldinho May 10 at 18:07
  • 1
    Note that in recent C++ Standards the compiler will perform (and usually perform in older Standards) some pretty slick magic (Copy Elision) to make this a particularly efficient way to return an object. – user4581301 May 10 at 18:47
  • Related question – αλεχολυτ May 12 at 12:44

Comments

Popular posts from this blog

Get current scroll position of ScrollView in React Native

React Native - Image Cache