What exactly was the rationale behind introducing references in c++?

后端 未结 5 1837
猫巷女王i
猫巷女王i 2021-01-03 17:26

From the discussion that has happened in my recent question (Why is a c++ reference considered safer than a pointer?), it raises another question in my mind: What exactly wa

5条回答
  •  日久生厌
    2021-01-03 18:24

    If code takes the address of a variable and passes it to a routine, the compiler has no way of knowing whether that address might get stored someplace and used long after the called routine has exited, and possibly after the variable has ceased to exist. By contrast, if code passes give a routine a reference to a variable, it has somewhat more assurance that the reference will only be used while that routine is running. Once that routine returns, the reference will no longer be used.

    Things end up getting a little 'broken' by the fact that C++ allows code to take the address of a reference. This ability was provided to allow compatibility with older routines which expected pointers rather than references. If a reference is passed to a routine which takes its address and stores it someplace, all bets are off. On the other hand, if as a matter of policy one forbids using the address of a reference in any way that might be persisted, one can pretty well gain the assurances that references provide.

提交回复
热议问题