I'm wondering if the following is valid:
#include <iostream>
#include <vector>
std::vector<int>& getVec()
{
static std::vector<int> vec{1, 2, 3, 4, 5};
return vec;
}
int main()
{
for (const auto& i : getVec())
{
std::cout << "i = " << i << std::endl;
}
return 0;
}
Basically I'm unsure about the lifetime of the temporary from getVec()
. I've looked at both this post and this one, but am in a bit of a different situation as my function returns a reference to static
data. Specifically, I'm wondering if scenario violates the following exception in the stated rule:
- A temporary bound to a reference parameter in a function call [...]
or if this is indeed safe code. I think it is safe, but just wanted to be sure.