Cppcoreguidelines: incorrect use of structured bindings from std::div_t

Created on 29 Jul 2020  路  9Comments  路  Source: isocpp/CppCoreGuidelines

At https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#example-c17
we see this:

auto [ quotient, remainder ] = div(123456, 73); // break out the members of the div_t result

This is wrong as std::div_t _et al._ don't have any defined order of their two members according to the Standard, so it's unreliable and error-prone to assume they'll be in that or any order, so we can't use structured bindings on them.

This should be rewritten to use a valid, not risky example.

Most helpful comment

the return type of std::div has properly named members too

Yes. And for that reason it would imho not be a good example, even if the order of its members were defined.

Then well-known domain-specific names could be used, rather than the same generic names of the members. Perhaps something like:

auto [apples_per_kid, leftover_apples] = std::div(apples, kids);

All 9 comments

Wow that is certainly surpising. I'm not sure div was the best example anyway since div_t already gives meaningful names to its data and used of those members still eschews a type specifier.

Perhaps std::minmax would be a good replacement?

div() would be a good example, and I'd use it thusly, _iff_ the order of members would be made defined - and hey, maybe someone on the committee could help with that ;-) ...but maybe there's an ASM reason not to.

The C committee owns that type not the C++ committee. The order of members (and the existence of other non-standard members) is left unspecified for many C types to allow pre-ANSI implementations to remain valid if they used a different order.

std::minmax might be good. Or std::set.insert (I think it's used elsewhere). Or std::to_chars to show something that's not a pair.

Or std::to_chars to show something that's not a pair

The return type of to_chars already has properly named members, so I see little benefit in using structured binding there.

the return type of std::div has properly named members too

the return type of std::div has properly named members too

Yes. And for that reason it would imho not be a good example, even if the order of its members were defined.

the return type of std::div has properly named members too

Yes. And for that reason it would imho not be a good example, even if the order of its members were defined.

Then well-known domain-specific names could be used, rather than the same generic names of the members. Perhaps something like:

auto [apples_per_kid, leftover_apples] = std::div(apples, kids);

Editors call: @cubbimew please update the example to something like container insert that returns a pair of iterator and bool. Thanks!

Was this page helpful?
0 / 5 - 0 ratings