scoped array原始碼剖析

2021-07-26 07:41:40 字數 1495 閱讀 6825

scoped_array很想scoped_ptr,它包裝了new操作符(不是單純的new)在堆上分配的動態陣列,為動態陣列提供了乙個**,保證可以正確的釋放記憶體。

scoped_array的原始碼如下:

namespace boost

~scoped_array() // never throws

void reset(t * p = 0) // never throws (but has a boost_assert in it, so not marked with boost_noexcept)

//過載了operator模擬陣列,但不支援*(p+i)這種訪問方式

t & operator(std::ptrdiff_t i) const

// never throws (but has a boost_assert in it, so not marked with boost_noexcept)

t * get() const boost_noexcept

// implicit conversion to "bool"

#include

void swap(scoped_array & b) boost_noexcept

};template

inline

void swap(scoped_array& a, scoped_array& b) boost_noexcept

} // namespace boost

上面的原始碼和我之前分析過的scoped_ptr類似,只不過變成了對陣列的封裝。scoped_array析構函式中的check_delete實現是這樣的:

template

inline

void checked_array_delete(t * x)

呵呵,這裡是delete x。

scoped_array的主要特點如下:

sceopd_array與scoped_ptr源於相同的設計思想,故而用法非常相似:它只能在被生命的作用域內使用,不能拷貝、賦值。唯一不同的是scoped_array包裝的是new產生的指標,並在析構時呼叫delete,因為它管理的是動態陣列,而不是單個物件

**示例:

class test
scoped_array過載了operator,因此用起來就像是乙個普通的陣列,但不能使用」首位址+n」的方式訪問元素,並且scoped_array不提供陣列索引的範圍檢查,如果使用超過動態陣列大小的索引或者是負數索引將引發未定義行為。

scoped_array沒有給程式增加額外的負擔,它的速度與原始陣列同樣快。但scoped_array功能很有限,不能動態增長。也沒有迭代器支援,不能搭配stl演算法,僅有乙個純粹的」裸」陣列介面。而且我們要盡量避免使用new操作符,盡量使用scoped_array,甚至是更好的std::vector。

參考:

spring security認證原始碼剖析

spring security 和shiro目前最主流的安全框架,很好的保護了系統的安全性。shiro實現的原理和spring security具有異曲同工之妙,學會乙個框架,另乙個框架也會很容易上手。1 spring security流程 usernamepasswordauthenticatio...

ReentrantLock獨佔鎖原始碼剖析

在開始分析reentrantlock 獨佔鎖之前,我們先來簡單了解幾個概念 悲觀鎖指對資料被外界修改持保守態度,認為資料很容易就會被其他執行緒修改,所以在資料被處理前先對資料進行加鎖,並在整個資料處理過程中,使資料處於鎖定狀態。例如synchronized。樂觀鎖是相對悲觀鎖來說對,它認為資料在一般...

locust對應原始碼HttpUser剖析(7)

老規矩,先貼 self.client session比較簡單,無非就是繼承了user的各個屬性,這裡把類變數client清空了,不再是noclientwarningraiser 了。其他都是繼續沿用,只是例項化的時候client變成了session。這個時候第乙個關注點就是,例項化的時候一定要有ho...