Adjacent constructors with a single argument: initializer_list and int

What determines which constructor should be used when initializing objects using this syntax; does it depend on the compiler? (Using VS2015):

Vector v { 3 };

I create my own class Vector(C ++ 11 training) and I have the following:

class Vector
{
public:
    Vector(initializer_list<double> lst);
    Vector(int s);
    // ...
private:
    double* elem;
    int sz;
};

and

int main()
{
    Vector v1 { 3 };  //calls init_list ctor
    Vector v2 { static_cast<int>(3)}; //calls init_list ctor
    Vector v3 = 3;    //call int ctor
}

My initial thought was to use syntax { 3 }that calls the constructor that accepts int, and then realized that it makes sense, since I could use something like { 3, 4, 5, 6 }that, and it would work - the passed array was seen as doubles, and an instance was created Vector.

: " {}-notation , int?" int, , , . , , init v3.

initializer_list<double>, , , v1 v2 , int .

, /? ? , int int double double*.

+3
1

. std::initializer_list , , .

Vector v3 = 3;

, int, int Vector. , , .

, , :

Vector v1 (3); //int constructor
Vector v2 {3}; //initializer_list constructor

, , , . , std::vector, , .

+5

Source: https://habr.com/ru/post/1622957/


All Articles