c++ 11是否可以安全返回initializer_list值?
我有一个简单的功能:
initializer_list<int> f(){return {1,2,3};}
G ++发出警告说:
warning: returning temporary initializer_list does not extend the lifetime of the underlying array [-Winit-list-lifetime]
返回{1,2,3}
是否存在风险? 感谢您的解释!
I've this simple function:
initializer_list<int> f(){return {1,2,3};}
g++ gives a warning saying:
warning: returning temporary initializer_list does not extend the lifetime of the underlying array [-Winit-list-lifetime]
Is there any risk to return an {1, 2, 3}
?
Thanks for explanations!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
initializer_list
的行为就像延长临时寿命的参考(临时是数组)。返回参考时,终身扩展名不适用,因此在这里也不适用。编译器是对的,返回的列表总是在悬空。
An
initializer_list
behaves like a reference extending lifetime of a temporary (the temporary being the array).Lifetime extension doesn't apply when returning references, so it doesn't apply here too. The compiler is right, the returned list is always dangling.