After seeing that a local reference-to-const may prolong the life of a temporary, I encountered the need to conditionally bind a local reference-to-const to either a function parameter or the temporary result of a function call, i.e.:
class Gizmo
{
// Rule of Five members implemented
};
Gizmo Frobnicate(const Gizmo& arg);
void ProcessGizmo(const Gizmo& arg, bool frobnicate)
{
const Foo& local = frobnicate ? Frobnicate(arg) : arg;
// Perform some work on local
}
A practical example: the boolean specifies whether to compress a buffer and you'd like to write uniform code that operates on local
either way.
The above example, however, invoked Gizmo's copy-constructor on arg
when frobnicate
was false
.
I managed to avoid the invocation of the copy-constructor by changing Frobnicate(arg)
to static_cast<const Gizmo&>(Frobnicate(arg))
.
My question becomes: how does the ternary operator interact with the rule about binding a local reference-to-const to a temporary? Is my solution legal and well-behaved?
const Foo& local = frobnicate ? static_cast<const Gizmo&>(Frobnicate(arg)) : arg;
Your solution is correct. Lifetime extension does propagate through static_cast
s, among other things, so this will not dangle.
The dangling observed in the other answer appears to be an old compiler bug, it doesn't happen in modern Clang, GCC, and MSVC.
Cppreference says it was always the case, I don't see any "since C++XX" or related defect reports in the link above.