What happens when C++ reference leaves its scope?

后端 未结 2 1579
别那么骄傲
别那么骄傲 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:49

    In C++ language the lifetime of the object the reference is bound to is not tied in any way to the lifetime of the reference itself, with only one exception (see below).

    If the object is destroyed before the reference is, the reference becomes invalid (like a hanging pointer). Any attempts to access that reference result in undefined behavior. This is what happens in your example.

    The the reference ends its lifetime before the object does, then... well, nothing happens. The reference disappears, the object continues to live.

    The only exception I was talking above is when a const reference is initialized with an immediate temporary object. In this case the lifetime of the temporary object become tied to the lifetime of the reference. When the reference dies, the object dies with it

    {
       const std::string& str = "Hello!"; 
       // A temporary `std::string` object is created here...
       ...
       // ... and it lives as long as the reference lives
       ...
    } // ... and it dies here, together with the reference
    

    P.S. You are using the term scope incorrectly. Scope is the visibility region for an identifier. Scope by itself has nothing to do with object lifetime. When something "leaves scope" in general case that something is not destroyed. It is a popular misconception to use the "leaves scope" wording to refer to the destruction point of an object.

提交回复
热议问题