Skip to main content

Posts

Showing posts from October, 2018

Chained Functions Break Reference Lifetime Extension

I discovered a reference lifetime extension gotcha. TL;DR; Chained functions (that return a reference to *this ) do not trigger C++ reference lifetime extension. Four ways out: First, don't rely on lifetime extension---make a copy; Second, have all chained functions return *this by-value; Third, use rvalue reference qualified overloads and have only them return by-value; Fourth, have a last chained ExtendLifetime() function that returns a prvalue (of type *this). C++ Reference Lifetime Extension C++ has a feature called "reference lifetime extension". Consider the following. std::array<std::string, 5> create_array_of_strings(); { const std::array &arr = create_array_of_strings(); // Only inspect arr here. } // arr out of scope. The temporary pointed to by arr destroyed here. The temporary std::array returned by create_array_of_strings() is not destroyed after the function returns. Instead the "lifetime" of the temporary std::array is ...