What happens when C++ reference leaves its scope?

后端 未结 2 1574
别那么骄傲
别那么骄傲 2020-12-03 10:34

If I interpret C++ references correctly, they are like pointers, but with guaranteed data integrity (no NULL, no (int*) 0x12345). But what happens when scope of referenced o

2条回答
  •  北海茫月
    2020-12-03 10:40

    this is undefined behavior and you were simply lucky that the memory for a hadn't been used for anything else yet. In a more complex scenario you would almost certainly get garbage. On my machine I get random garbage with this code. For me, this is likely because I am using a 64-bit machine which uses a register calling convention. Registers get re-used much more often than main memory (ideally...).

    So to answer your question of "what happens". Well in this scenario, the reference is likely little more than a limited pointer with friendlier syntax :-). Under the hood the address of a is stored. Later the a object goes out of scope, but the B object's reference to that a will not be "auto-magically" updated to reflect this. Hence you have an invalid reference now.

    Using this invalid reference will yield just about anything, sometimes crashes, sometimes just bunk data.


    EDIT: Thanks to Omnifarious, I've been thinking about this. There is a rule in c++ that basically says that if you have a const reference to a temporary, then the lifetime of the temporary is at least as long as the const reference. Which introduced a new question.

    EDIT: Moved to separate question for those interested (const reference to temporary oddity)

提交回复
热议问题