...

/

Exception safety guarantees

Exception safety guarantees

This part discusses exception safety with an example!

We'll cover the following...

So far everything looks nice and smooth… but what happens when there’s an exception during the creation of the alternative in a variant?

Example:

Press + to interact
#include <iostream>
#include <string>
#include <variant>
using namespace std;
class ThrowingClass
{
public:
explicit ThrowingClass(int i) {
if (i == 0) throw int (10);
}
operator int () {
throw int(10);
}
};
int main(int argc, char** argv)
{
std::variant<int, ThrowingClass> v;
// change the value:
try
{
v = ThrowingClass(0);
}
catch (...)
{
std::cout << "catch(...)\n";
// we keep the old state!
std::cout << v.valueless_by_exception() << '\n';
std::cout << std::get<int>(v) << '\n';
}
// inside emplace
try
{
v.emplace<0>(ThrowingClass(10)); // calls the operator int
}
catch (...)
{
std::cout << "catch(...)\n";
// the old state was destroyed, so we're not in invalid state!
std::cout << v.valueless_by_exception() << '\n';
}
return 0;
}

In the first case - with the assignment operator - the ...