C++ has a lesser-known feature where binding a temporary object to a const reference extends the temporary's lifetime to match the reference's scope. This is an official C++ standard behavior, unlike the undefined behavior of holding a non-const reference to a stack-allocated local. An interesting side effect: when a const Base reference holds a temporary Foo object, the correct Foo destructor is called even without virtual destructors, effectively providing polymorphic destruction for free. This feature also extends to rvalue references (&&) in modern C++, and was notably used by Andrei Alexandrescu in his ScopeGuard pattern for exception-safe programming.
Sort: