Can I store a copy of std :: initializer_list? What is the reason?

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

  • the underlying data is highlighted in the current frame of the function (because the pointer to the first element says so)
  • returns the value of initializer_list by function from the function does not change the value of the pointer (which leads to the conclusion that the data is not copied along with initializer_list).

This makes it impossible to copy initializer_list , if the copy can survive the original object .

  • Will this behavior be supported in the future by the release of the C ++ standard?
  • And just as importantly, what would be the reason for this behavior? (Today it’s very hard for me, so I would naively say that this contradicts the beloved principle of “least surprise”).
+6
source share
1 answer

From the standard C ++ 11, 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 length will be obvious representations for initializer_list. initializer_list is used to implement initializer lists, as specified in 8.5.4. Copying the list of initializers does not copy the basic elements. - end of note]

This is similar to finding pointers to objects. You can also make the pointer outlive the object. If you want to make it "safe", take / save the vector of elements.

Copying elements would make it expensive, and therefore no one would use it. Accessible documentation allows you to clearly understand what it is doing.

EDIT:

This is a Stroustrup proposal for initializer_list : N2100 . Reading can enlighten his design decisions.

+8
source

Source: https://habr.com/ru/post/978750/


All Articles