mercredi 31 janvier 2018

Why the move assignment of std::initializer_list was not blocked?

It is clear that std::initializer_list is not an actual container. The standard defines clearly what you can and cannot do with std::initializer_list.

But why does the language keep the option of doing foolish things, like assigning a temporary std::initializer_list into another - when it could have been easily blocked with =delete on std::initializer_list's move assignment operator?

Here is a broken code example, that compiles:

void foo(std::initializer_list<int> v) {
    std::cout << *v.begin() << std::endl;
}

int main() {
    int a = 1, b = 2, c = 3;
    auto val = {a, b, c}; // ok, extending the lifetime of {a, b, c}
    foo(val); // prints ok
    int i = 7;
    val = {i}; // doesn't handle well assignment of temporary
    foo(val); // prints garbage...
}

Aucun commentaire:

Enregistrer un commentaire