jeudi 23 juillet 2015

Uniform initialization behavior different for different types in vector

I came across this article in which I read this example by one of the posters. I have quoted that here for convenience.

struct Foo
{
    Foo(int i) {} // #1
    Foo() {}
};

int main()
{
    std::vector<Foo> f {10};

    std::cout << f.size() << std::endl;
}

The above code, as written, emits “1” (10 is a converted to Foo by a constructor that takes an int, then the vector’s initializer_list constructor is called). If I comment out the line commented as #1, the result is “10” (the initializer_list cannot be converted so the int constructor is used).

My question is why does it emit a 10 if the int constructor is removed. I understand that uniform initialization list works in the following order

1-Calls the initializer list if available or possible
2-Calls the default constructor if available
3-Does aggregate initialization

In the above case why is it creating 10 items in the vector since 1,2 and 3 are not possible ? Does this mean with uniform initialization a vector of items might always have different behaviors ?

Aucun commentaire:

Enregistrer un commentaire