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?