skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
cpp-reference-lifetime-extension
This page is read only. You can view the source, but not change it.
# C++ reference lifetime extension **[Reference lifetime extension](https://en.cppreference.com/w/cpp/language/reference_initialization)** 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. ## Example This example shows how const references extend the lifetime of temporaries. ```cpp // 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; } ```
Page Tools
Show pagesource
Backlinks
Back to top