Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

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

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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...