How exception-safe is std::tie?
Asked Answered
S

1

10

std::tie returns a tuple of references, so you can do the following:

int foo, bar, baz;
std::tie(foo, bar, baz) = std::make_tuple(1, 2, 3);

This is similar to foo, bar, baz = (1, 2, 3) in Python.

What is supposed to happen if one of the assignments throws, as in the following example?

int foo = 1337;
struct Bar {
    Bar& operator=(Bar) { throw std::exception{}; }
} bar;
try {
    std::tie(foo, bar) = std::make_tuple(42, Bar{});
} catch (std::exception const&) {
    std::cout << foo << '\n';
}

Will it print 1337 or 42, or is this unspecified?

Shive answered 8/12, 2012 at 15:49 Comment(1)
Since the layout of tuple is unspecified, I imagine the answer here is also "unspecified".Lilongwe
Y
5

The Standard speaks of tuple assignment art §20.4.2.2 [tuple.assign], the only mention of exception is that the assignment should not throw unless one of the elements assigned to throws.

Since there is no mention of the order in which elements are assigned to, it is thus unspecified.

Yser answered 8/12, 2012 at 16:25 Comment(1)
For most cases I would argue that the basic exception guarantee is provided as long as the types involved provide the basic exception or better. Also obviously you get nothrow iff everything is nothrow -- that's specified.Saloop

© 2022 - 2024 — McMap. All rights reserved.