2

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
J. Tarasov
  • 79
  • 1
  • 7
  • BTW it is true for primitives too. `int &x = 42;` leads to a compilation error. – Zefick Nov 27 '19 at 10:01
  • 1
    To quote the most salient part of the dupe: _"It's just that the designers felt that it would cause a sufficient number of problems (probably due to the common idiom of 'out parameters') without enabling anything of similar value, so they simply made a design decision to prohibit temporaries binding to non-const references."_ – Max Langhof Nov 27 '19 at 10:15
  • In case you are unaware, you can do `obj&& ref = obj();` (and `int&& x = 42;`) – M.M Nov 27 '19 at 10:32

0 Answers0