保留std :: initializer_list的副本可以安全吗?理由是什么? [英] Can it be safe to keep a copy of an std::initializer_list? What is the rationale?

查看:56
本文介绍了保留std :: initializer_list的副本可以安全吗?理由是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的环境中, std :: initializer_list 实现为指向第一个元素和大小的指针。仍然在我的特定设置中,我能够观察到:

In my environment, the std::initializer_list is implemented as a pointer to the first element, and a size. Still in my specific setup, I was able to observe that:


  • 基础数据分配在当前函数框架中(因为指向第一个元素是这样的)

  • 通过函数的值返回 initializer_list 不会更改指针的值(导致结论是数据不会与initializer_list一起复制。)

  • the underlying data is allocated in the current function frame (because the pointer to the first element says so)
  • returning an initializer_list by value from a function does not change the value of the pointer (leading to the conclusion that the data is not copied alongside the initializer_list).

这使得复制 initializer_list不安全如果副本可以超过原始对象


  • 这种行为是否会

  • 同样重要的是,这种行为背后的原理是什么? (今天真的让我很难受,所以我天真地说这违背了最少惊讶的心爱原则)

推荐答案

根据C ++ 11标准18.9 [support.initlist]:

From the C++11 standard, 18.9 [support.initlist]:


2 类型为initializer_list的对象提供对const E类型的对象数组的访问。[注:一对指针或一个指针加上一个长度显然是initializer_list的表示形式。 initializer_list用于实现8.5.4中指定的初始化程序列表。 复制初始化程序列表不会复制基础元素。 —结束语]

2 An object of type initializer_list provides access to an array of objects of type const E. [ Note: A pair of pointers or a pointer plus a length would be obvious representations for initializer_list. initializer_list is used to implement initializer lists as specified in 8.5.4. Copying an initializer list does not copy the underlying elements. — end note ]

这就像将指针指向对象。您还可以使指针超出对象的寿命。如果您想安全地进行操作,请改用/存储一个元素向量。

It's like taking pointers to objects. You can also make the pointer outlive the object. If you want to do it "safely", take/store a vector of elements instead.

复制元素会使其变得昂贵,因此没人会使用它。 可用的文档非常清楚其功能。

Copying the elements would make it expensive, and thus nobody would use it. The documentation available makes it very clear about what it does.

编辑:

这是Stroustrup对 initializer_list N2100 。阅读它可能会启发其设计决策。

This is Stroustrup's proposal for initializer_list: N2100. Reading it might enlighten on its design decisions.

这篇关于保留std :: initializer_list的副本可以安全吗?理由是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆