vendredi 20 décembre 2019

Is it safe to swap two different vectors in C++, using the std::vector::swap method?

Suppose that you have the following code:

int main()
{
    std::vector<std::string> First{"example", "second" , "C++" , "Hello world" };
    std::vector<std::string> Second{"Hello"};

    First.swap(Second);

    for(auto a : Second) std::cout << a << "\n";
    return 0;
}

Imagine the vector are not std::string, yet classes:

std::vector<Widget> WidgetVector;

std::vector<Widget2> Widget2Vector;

Is it still safe to swap the two vectors with the std::vector::swap method: WidgetVector.swap(Widget2Vector); or it will lead to an UB?

Aucun commentaire:

Enregistrer un commentaire