std::vector<int>GetInts();for(inti:GetInts()){}// lifetime extension on the vector is important// Return string_views of size 1 for each char in this string.std::vector<absl::string_view>Explode(conststring&s);// vector中的string_view的生命周期并没有被延长// Lifetime extension kicks in on the vector, but *not* on the temporary string!for(absl::string_views:Explode(StrCat("oo","ps"))){}// WRONG
下面则无法正常工作:
1 2 3 4 5 6 7 8 910
MyProtoGetProto();// sub_protos获取到的子对象没办法进行生命周期的延长,MyProto对象在语句结束时就已经被销毁了。// Lifetime extension *doesn't work* here: sub_protos (a repeated field)// is destroyed by MyProto going out of scope, and the lifetime extension rules// don't kick in here to magically lifetime extend the MyProto returned by// GetProto(). The sub-object lifetime extension only works for simple// is-a-member-of relationships: the compiler doesn't see that sub_protos()// itself returning a reference to an sub-object of the outer temporary.for(constSubProto&p:GetProto().sub_protos()){}// WRONG