欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++ vector擴(kuò)容解析noexcept應(yīng)用場景

 更新時(shí)間:2020年09月19日 09:47:59   作者:張雅宸  
這篇文章主要介紹了C++ vector擴(kuò)容解析noexcept應(yīng)用場景,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

c++11提供了關(guān)鍵字noexcept,用來指明某個(gè)函數(shù)無法——或不打算——拋出異常:

void foo() noexcept; // a function specified as will never throw
void foo2() noexcept(true); // same as foo
void bar(); // a function might throw exception
void bar2() noexcept(false); // same as bar

所以我們需要了解以下兩點(diǎn):

noexcept有什么優(yōu)點(diǎn),例如性能、可讀性等等。

需不需要在代碼中大量使用noexcept。

noexcept優(yōu)點(diǎn)

我們先從std::vector入手來看一下第一點(diǎn)。

我們知道,vector有自己的capacity,當(dāng)我們調(diào)用push_back但是vector容量滿時(shí),vector會(huì)申請(qǐng)一片更大的空間給新容器,將容器內(nèi)原有的元素copy到新容器內(nèi):

但是如果在擴(kuò)容元素時(shí)出現(xiàn)異常怎么辦?

申請(qǐng)新空間時(shí)出現(xiàn)異常:舊vector還是保持原有狀態(tài),拋出的異常交由用戶自己處理。

copy元素時(shí)出現(xiàn)異常:所有已經(jīng)被copy的元素利用元素的析構(gòu)函數(shù)釋放,已經(jīng)分配的空間釋放掉,拋出的異常交由用戶自己處理。

這種擴(kuò)容方式比較完美,有異常時(shí)也會(huì)保持上游調(diào)用push_back時(shí)原有的狀態(tài)。

但是為什么說比較完美,因?yàn)檫@里擴(kuò)容還是copy的,當(dāng)vector內(nèi)是一個(gè)類且持有資源較多時(shí),這會(huì)很耗時(shí)。所以c++11推出了一個(gè)新特性:move,它會(huì)將資源從舊元素中“偷”給新元素(對(duì)move不熟悉的同學(xué)可以自己查下資料,這里不展開說了)。應(yīng)用到vector擴(kuò)容的場景中:當(dāng)vector中的元素的移動(dòng)拷貝構(gòu)造函數(shù)是noexcept時(shí),vector就不會(huì)使用copy方式,而是使用move方式將舊容器的元素放到新容器中:

利用move的交換類資源所有權(quán)的特性,使用vector擴(kuò)容效率大大提高,但是當(dāng)發(fā)生異常時(shí)怎么辦:
原有容器的狀態(tài)已經(jīng)被破壞,有部分元素的資源已經(jīng)被偷走。若要恢復(fù)會(huì)極大增加代碼的復(fù)雜性和不可預(yù)測性。所以只有當(dāng)vector中元素的move constructor是noexcept時(shí),vector擴(kuò)容才會(huì)采取move方式來提高性能。

剛才總結(jié)了利用noexcept如何提高vector擴(kuò)容。實(shí)際上,noexcept還大量應(yīng)用在swap函數(shù)和move assignment中,原理都是一樣的。

noexcept使用場景

上面提到了noexcept可以使用的場景:

  • move constructor
  • move assignment
  • swap

很多人的第一念頭可能是:我的函數(shù)現(xiàn)在看起來明顯不會(huì)拋異常,又說聲明noexcept編譯器可以生成更高效的代碼,那能加就加唄。但是事實(shí)是這樣嗎?

這個(gè)問題想要討論清楚,我們首先需要知道以下幾點(diǎn):

函數(shù)自己不拋異常,但是不代表它們內(nèi)部的調(diào)用不會(huì)拋出異常,并且編譯器不會(huì)提供調(diào)用者與被調(diào)用者的noexcept一致性檢查,例如下述代碼是合法的:

void g(){
  ...    //some code
}
void f() noexcept
{
  … 			//some code
  g();
}

當(dāng)一個(gè)聲明為noexcept的函數(shù)拋出異常時(shí),程序會(huì)被終止并調(diào)用std::terminate();

所以在我們的代碼內(nèi)部調(diào)用復(fù)雜,鏈路較長,且隨時(shí)有可能加入新feature時(shí),過早給函數(shù)加上noexcept可能不是一個(gè)好的選擇,因?yàn)閚oexcept一旦加上,后續(xù)再去掉也會(huì)變得困難 : 調(diào)用方有可能看到你的函數(shù)聲明為noexcept,調(diào)用方也會(huì)聲明為noexcept。但是當(dāng)你把函數(shù)的noexcept去掉卻沒有修改調(diào)用方的代碼時(shí),當(dāng)異常拋出到調(diào)用方會(huì)導(dǎo)致程序終止。

目前主流的觀點(diǎn)是:

加noexcept

函數(shù)在c++98版本中已經(jīng)被聲明為throw()

上文提到過的三種情況:move constructor、move assignmemt、swap。如果這些實(shí)現(xiàn)不拋出異常,一定要使用noexcept。
leaf function. 例如獲取類成員變量,類成員變量的簡單運(yùn)算等。下面是stl的正向iterator中的幾個(gè)成員函數(shù):

# if __cplusplus >= 201103L
# define _GLIBCXX_NOEXCEPT noexcept
# else
# define _GLIBCXX_NOEXCEPT

 reference
   operator*() const _GLIBCXX_NOEXCEPT
   { return *_M_current; }

   pointer
   operator->() const _GLIBCXX_NOEXCEPT
   { return _M_current; }

   __normal_iterator&
   operator++() _GLIBCXX_NOEXCEPT
   {
	++_M_current;
	return *this;
   }

   __normal_iterator
   operator++(int) _GLIBCXX_NOEXCEPT
   { return __normal_iterator(_M_current++); }

不加noexcept

除了上面的要加的情況,其余的函數(shù)不要加noexcept就可以。

最后我們看一下vector如何實(shí)現(xiàn)利用noexcept move constructor擴(kuò)容以及move constructor是否聲明noexcept對(duì)擴(kuò)容的性能影響。

如何實(shí)現(xiàn)利用noexcept move constructor擴(kuò)容

這里就不貼大段的代碼了,每個(gè)平臺(tái)的實(shí)現(xiàn)可能都不一樣,我們只關(guān)注vector是怎么判斷調(diào)用copy constructor還是move constructor的。

其中利用到的核心技術(shù)有:

  • type trait
  • iterator trait
  • move iterator
  • std::forward

核心代碼:

template <typename _Iterator, typename _ReturnType = typename conditional<
                 __move_if_noexcept_cond<typename iterator_traits<_Iterator>::value_type>::value,
                 _Iterator, move_iterator<_Iterator>>::type>
inline _GLIBCXX17_CONSTEXPR _ReturnType __make_move_if_noexcept_iterator(_Iterator __i) {
 return _ReturnType(__i);
}

template <typename _Tp>
struct __move_if_noexcept_cond
  : public __and_<__not_<is_nothrow_move_constructible<_Tp>>, is_copy_constructible<_Tp>>::type {};

這里用type trait和iterator trait聯(lián)合判斷:假如元素有noexcept move constructor,那么is_nothrow_move_constructible=1 => __move_if_noexcept_cond=0 => __make_move_if_noexcept_iterator返回一個(gè)move iterator。這里move iterator迭代器適配器也是一個(gè)c++11新特性,用來將任何對(duì)底層元素的處理轉(zhuǎn)換為一個(gè)move操作,例如:

std::list<std::string> s;
std::vector<string> v(make_move_iterator(s.begin()),make_move_iterator(s.end())); //make_move_iterator返回一個(gè)std::move_iterator

然后上游利用生成的move iterator進(jìn)行循環(huán)元素move:

{
 for (; __first != __last; ++__first, (void)++__cur) std::_Construct(std::__addressof(*__cur), *__first);
 return __cur;
}

template <typename _T1, typename... _Args>
inline void _Construct(_T1 *__p, _Args &&... __args) {
 ::new (static_cast<void *>(__p)) _T1(std::forward<_Args>(__args)...);   //實(shí)際copy(或者move)元素
}

其中_Construct就是實(shí)際copy(或者move)元素的函數(shù)。這里很關(guān)鍵的一點(diǎn)是:對(duì)move iterator進(jìn)行解引用操作,返回的是一個(gè)右值引用。,這也就保證了,當(dāng)__first類型是move iterator時(shí),用_T1(std::forward<_Args>(__args)...進(jìn)行“完美轉(zhuǎn)發(fā)”才調(diào)用_T1類型的move constructor,生成的新對(duì)象被放到新vector的__p地址中。

總結(jié)一下過程就是:

利用type trait和iterator trait生成指向舊容器的normal iterator或者move iterator

循環(huán)將舊容器的元素搬到新容器。如果指向舊容器的是move iterator,那么解引用會(huì)返回右值引用,會(huì)調(diào)用元素的move constructor,否則調(diào)用copy constructor。

大家可以用下面這段簡單的代碼在自己的平臺(tái)打斷點(diǎn)調(diào)試一下:

class A {
 public:
 A() { std::cout << "constructor" << std::endl; }
 A(const A &a) { std::cout << "copy constructor" << std::endl; }
 A(const A &&a) noexcept { std::cout << "move constructor" << std::endl; }
};

int main() {
 std::vector<A> v;
 for (int i = 0; i < 10; i++) {
  A a;
  v.push_back(a);
 }

 return 0;
}

noexcept move constructor對(duì)性能的影響

這篇文章C++ NOEXCEPT AND MOVE CONSTRUCTORS EFFECT ON PERFORMANCE IN STL CONTAINERS介紹了noexcept move constructor對(duì)耗時(shí)以及內(nèi)存的影響,這里不重復(fù)贅述了,感興趣的可以自己試一下。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論