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