Can it be safe to keep a copy of an std::initializer_list? What is the rationale?

前端 未结 1 1060
天涯浪人
天涯浪人 2020-12-20 17:04

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 tha

相关标签:
1条回答
  • 2020-12-20 17:33

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

    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.

    EDIT:

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

    0 讨论(0)
提交回复
热议问题