←back to thread

178 points todsacerdoti | 6 comments | | HN request time: 0s | source | bottom
1. MauranKilom ◴[] No.26341332[source]
Random emplace_back hate: I really dislike how you can't use it for objects that you'd normally use aggregate initialization for.

See https://godbolt.org/z/6qW7q3

    struct SimpleData
    {
        int a;
        double b;
    };

    SimpleData someData = {1, 2.0}; // ok

    std::vector<SimpleData> data;

    // Why can I not do this?
    data.emplace_back(1, 2.0);
replies(3): >>26341692 #>>26344690 #>>26347384 #
2. Koshkin ◴[] No.26341692[source]
To be fair, push_back won’t help you here, either.
replies(1): >>26341778 #
3. MauranKilom ◴[] No.26341778[source]
It does, actually. In fact, this is the most concise one (see godbolt link):

    data.push_back({1, 2.0});
That does not work with emplace_back (not that it would be useful) because the template arguments can't be deduced from the initializer list (whereas for push_back the type is known so you can initialize it with the initializer list).
replies(1): >>26343145 #
4. Koshkin ◴[] No.26343145{3}[source]
You are correct, the problem is exclusively with emplace_back; incidentally, there is an "official" discussion of this at https://cplusplus.github.io/LWG/issue2089.
5. vinkelhake ◴[] No.26344690[source]
You can as of C++20 - aggregate initialization has been extended to support T(x, y) syntax.

See https://godbolt.org/z/Tj5baM and https://en.cppreference.com/w/cpp/language/aggregate_initial... (case 5).

6. gpderetta ◴[] No.26347384[source]
That's because of the epic fail that are initializer lists that prevent aggregate initialization (which is otherwise awesome) to be used safely in generic contextes.