Search⌘ K
AI Features

Exception safety guarantees

Explore the concept of exception safety guarantees within std::variant in C++17. Understand how exceptions can affect the variant's state during assignment and emplacement, what a valueless-by-exception variant means, and the implications for accessing variant values after exceptions. This lesson helps you safely manage and use std::variant in your C++ programs.

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:

C++ 17
#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 ...