C++(23):延长for循环临时变量生命期
C++:通过const T&延长临时对象的生命期-CSDN博客
const int& r = getS().getX();
这种形式是无法通过const T&延长临时对象的生命期的
#include <vector>
#include <string>
#include <iostream>
using namespace std;struct S
{vector<int> vec;const vector<int>& getVector() const {return vec;}
};S getS()
{S s;s.vec = {1, 2, 3, 4, 5};return s;
}int main()
{for (auto n : getS().getVector()){cout << n << " ";}cout << endl;return 0;
}
编译:g++ -O0 -g -fsanitiz
