Search⌘ K
AI Features

Reference Lifetime Extension

Explore the concept of reference lifetime extension in C++17 to understand how temporary objects can safely bind to const references, including practical examples involving std::string_view. This lesson explains lifetime rules for temporaries, common pitfalls with string_view, and best practices to ensure object validity in your code.

We'll cover the following...

What happens in the following case:

C++ 17
#include <iostream>
#include <vector>
using namespace std;
std::vector<int> GenerateVec() {
return std::vector<int>(5, 1);
}
int main() {
const std::vector<int>& refv = GenerateVec();
cout << refv.size();
}

Is the above code safe?

Yes - the C++ rules say that the lifetime of a temporary object bound to a const reference is prolonged to the lifetime of the reference itself.

Here’s a full example quoted ...