I looked through this famous language problem on stackoverflow, but found only statements like "the rule exists", not the rationale. So the question is: imagine I have a non-primitive type obj
and do the following:
obj& ref = obj();
I'm naturally not allowed to do this, but why? As I understand it, temporary obj
is constructed on stack memory, so why not allow modifications of this while ref
is in scope and object still lives?
(I'm assuming obj
would be created on stack, because if obj
type is big enough then at some point only stack memory would be big enough to store it)
Another unclear point for me is - why allowing the same with const modifier:
const obj& ref = obj();
obj
will still be temporary, will still live only within the scope of ref, so no apparent reasons for the behavior on two completely identical obj
's to differ - if they work and live identically why should we treat them differently?
I guess I will be receiving a lot of answers like "so you could construct the object in place and pass it to a function like this:"
void f(const obj& ref) {
do something
}
int main() {
f(obj());
}
but my question still holds, because in my understanding even if we passed in-place constructed object by non-const reference, we could freely modify something on stack without any troubling consequences - programmer should just be aware that this object is temporary and modifications will probably be lost (but might not be temporary so modifications are completely sensible!).
To simplify matters a bit, I assume obj
type does not allocate any heap memory and is trivially constructible and copiable.