Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the principle of C++ std::initializer_list implementation?

Shulou Source: shulou.com Published: 2022-06-01 19:31:46 09月23日 Update

This article mainly explains "what is the principle of C++ std::initializer_list implementation". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the implementation principle of C++ std::initializer_list".

The implementation principle of std::initializer_list:

/ / initializer_list template class initializer_list {public: typedef _ E value_type; typedef const_ E& reference; typedef const_ E& const_reference; typedef size_t size_type; typedef const_ E* iterator; typedef const_ E* const_iterator; private: iterator _ M_array Size_type _ The compiler can call a private constructor. Constexpr initializer_list (const_iterator _ a, size_type _ l): _ M_array (_ a), _ M_len (_ l) {} constexpr initializer_list () noexcept: _ M_array (0), _ M_len (0) {} / / Number of elements. Constexpr size_type size () const noexcept {return _ First element;} / First element. Constexpr const_iterator begin () const noexcept {return _ multiple array;} / / One past the last element. End () const noexcept {return begin () + size ();}}

He believes that the compiler constructs a std::array before constructing std::initializer_list, and then uses begin () and size () of std::array to construct std::initializer_list. There is a mistake in this statement. Instead of constructing std::array, the compiler constructs an array const T [N] directly on the stack. Arrays constructed on the stack, like other variables, are automatically destructed when they leave scope, eliminating the need to manually manage memory, so there is no need to use std::array at all.

This is the description of cppreference.com:

The underlying array is a temporary array of type const T [N]

Specifically, it is an ordinary array.

This is the description of N3337:

An object of type initializer_list provides access to an array of objects of type const E.

It didn't say std::array.

Thank you for your reading, the above is the content of "what is the implementation principle of C++ std::initializer_list". After the study of this article, I believe you have a deeper understanding of what the implementation principle of C++ std::initializer_list is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Principles Clearing learning content arrays compilers yes compiling normal necessary functions memory variables that is ideas situations manual articles are in more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Microsoft vpn NVidia Shulou Information