Reference lifetime extension is a special rule where binding a temporary to a const reference extends the temporary's lifetime to the lifetime of the reference. This allows safely using temporary objects in references without dangling references.
Exploit reference lifetime extension in function parameters and member initializers; don't bind non-const references to temporaries.
This example shows how const references extend the lifetime of temporaries.
// compile: g++ -o reflife reflife.cpp // run: ./reflife // description: const reference binds temporary and extends its lifetime #include <iostream> #include <string> class View { private: const std::string& str; public: View(const std::string& s) : str(s) {} // temporary extended void print() { std::cout << str << "\n"; } }; int main() { { View v(std::string("temporary")); // temp extended until v destroyed v.print(); // safe: temporary still alive } // temporary destroyed here with v // Dangerous (if allowed): // const std::string& ref = std::string("temp"); // lifetime ends immediately return 0; }