Can it be safe to keep a copy of an std::initializ

2019-02-22 01:37发布

问题:

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:

  • 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).

This is making it unsafe to copy an initializer_list, if the copy can outlive the original object.

  • Will this behavior be maintained by further releases of the C++ standard ?
  • And equally important, what would be the rationale behind this behaviour ? (it bit me really hard today, so I would naïvely say it goes against the beloved principle of "least astonishment")

回答1:

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.