-1

Recently, I saw below code snippet in a project. I can't paste the project code directly but write a similar one instead. I can't understand why "fun(A{a});" can pass the compilation and works:(. Does anyone know such C++ feature? What does "A{a}" mean? Thanks very much!

class A {
public:
    int x = 10;
    int y = 20;
};

void fun(A a) {
    cout << "A.x = " << a.x << endl;
    cout << "A.y = " << a.y << endl;
}

int main() {
    A a;
    fun(A{a});
    return 0;
}
Alex. Liu
  • 59
  • 4
  • I believe that's list initialization. More information here: http://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives – Alex Johnson Dec 08 '16 at 06:46
  • Thanks for your kindly reply:). At the beginning, I also thought it should be list initialization. But I still can't find any evidence that says that we can put the class name in front of the "{}". I also made a test. I added the list initializer constructor into the class. But unfortunately, it wasn't invoked. So I rose this question. – Alex. Liu Dec 08 '16 at 06:51
  • That's a curly braces initializer, syntax introduced in C++11. C++03 had no way to directly initialize a temporary POD. One had to resort to silly factory functions. This particular example copy constructs the temporary. – Cheers and hth. - Alf Dec 08 '16 at 06:54
  • My confusion is "Can we put the class name in front of the curly braces?". Is there any official explanation for this syntax? – Alex. Liu Dec 08 '16 at 06:58
  • see [the documentation](http://en.cppreference.com/w/cpp/language/initializer_list) – slawekwin Dec 08 '16 at 07:16
  • 1
    Great thanks, guys! especially for @slawekwin. And I found a more direct explanation from this link http://en.cppreference.com/w/cpp/language/list_initialization – Alex. Liu Dec 08 '16 at 09:14
  • @Alex.Liu why don't you write an answer summing up what you found? – slawekwin Dec 08 '16 at 09:56
  • @slawekwin. No problem. Thanks for the kindly reminder:) – Alex. Liu Dec 09 '16 at 01:11

1 Answers1

2

Thanks for everyone's help, especially for @slawekwin!:) I finally find the answer.

T { arg1, arg2, ... }; is a kind of list initialization, which creates an unnamed temporary. for more information, please refer to this link.

slawekwin
  • 6,270
  • 1
  • 44
  • 57
Alex. Liu
  • 59
  • 4