void inc(int &n) {
n++;
}
Consider the above function. If I were to call it with an rvalue, C++ would shout at me. For example inc(1)
.
It seems perfectly reasonable for the standard to have been that a temporary is created, and dropped at the end of the function's execution (as you currently have to manually do).
In fact, other languages already do this. Consider Rust
fn inc(n: &mut i32) {
*n += 1;
}
Here, calling inc(&mut 1)
is perfectly valid.
What is especially interesting is that C++ allows this sort of pattern for const
references. So the only function I can imagine this having is to indicate to the caller that they are throwing away an effect of the function. However, we have to explicitly issue at most warnings with [[nodiscard]]
for ignored return values...
I am sure I am missing something C++-ish that I don't understand quite yet! What kind of good reasons are there for having the standard be this way, instead of, for example, requiring [[nodiscard]]
on parameters like we do with return values?