C++ std::initializer_list 實(shí)現(xiàn)原理解析及遇到問題
一般而言,對變量或?qū)ο笫褂美ㄌ柍跏蓟姆绞奖环Q為直接初始化,其本質(zhì)是調(diào)用了相應(yīng)的構(gòu)造函數(shù);而使用等號初始化的方式則被稱為拷貝初始化,說到拷貝大家可能馬上就會(huì)想到拷貝構(gòu)造函數(shù)、operator =()函數(shù),但此時(shí)并不一定是調(diào)用了這兩個(gè)函數(shù),這點(diǎn)極容易混淆?。?!
今天正在看侯捷《C++ 新標(biāo)準(zhǔn) C++11-14》的視頻,里面講到 std::initializer_list
的實(shí)現(xiàn)原理,并且把源碼貼出來。
/// initializer_list template<class _E> 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 _M_len; // 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 _M_len; } // First element. constexpr const_iterator begin() const noexcept { return _M_array; } // One past the last element. end() const noexcept { return begin() + size(); } };
他認(rèn)為,構(gòu)造 std::initializer_list
之前編譯器會(huì)先構(gòu)造一個(gè) std::array
,然后使用 std::array
的 begin()
和 size()
構(gòu)造 std::initializer_list
。這種說法有一處錯(cuò)誤。編譯器不會(huì)構(gòu)造 std::array
,而是在棧上直接構(gòu)造一個(gè)數(shù)組 const T[N]
。在棧上構(gòu)造的數(shù)組會(huì)像其他變量一樣,在離開作用域時(shí)自動(dòng)析構(gòu),不需要手動(dòng)管理內(nèi)存,所以根本沒必要使用 std::array
。
這個(gè)是 cppreference.com 的描述:
The underlying array is a temporary array of type
const T[N]
明確地說是普通的 array
。
這個(gè)是 N3337 的描述:
An object of type
initializer_list<E>
provides access to an array of objects of typeconst E
.
并沒有說是 std::array
。
到此這篇關(guān)于C++ std::initializer_list 實(shí)現(xiàn)原理勘誤的文章就介紹到這了,更多相關(guān)C++ std::initializer_list 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言完整實(shí)現(xiàn)12種排序算法(小結(jié))
本文主要介紹了C語言完整實(shí)現(xiàn)12種排序算法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05C語言+shell實(shí)現(xiàn)linux網(wǎng)卡狀態(tài)檢測
這篇文章主要為大家詳細(xì)介紹了C語言+shell實(shí)現(xiàn)linux網(wǎng)卡狀態(tài)檢測,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06C語言怎么連接兩個(gè)數(shù)組的內(nèi)容你知道嗎
這篇文章主要為大家介紹了C語言怎么連接兩個(gè)數(shù)組的內(nèi)容,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-01-01