c++ 11是否可以安全返回initializer_list值?

发布于 2025-02-10 08:08:48 字数 304 浏览 2 评论 0原文

我有一个简单的功能:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

葬花如无物 2025-02-17 08:08:48

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文