vendredi 23 septembre 2016

Exception in std::vector<>::emplace_back() safe?

What happens when an exception is thrown in std::vector<>::emplace_back()?

For example:

class Foo {
public:
  Foo(int bar) {
    if (bar == 4) throw std::exception("Something went wrong");
  }
}

and

std::vector<std::unique_ptr<Foo>> foo_list;
foo_list.emplace_back(new Foo(3));
try {
  foo_list.emplace_back(new Foo(4));
} catch (std::exception error) {
  // How bad is it?
}
// Whats inside foo_list now?

I would expect the vector to just contain the first Foo object.

Is this the case? And is this guaranteed by the standard?

And also: Could there be any memory leaks?

Aucun commentaire:

Enregistrer un commentaire