QCache 類是提供緩存的模闆類。 更多...
| 頭: | #include <QCache> |
| qmake: | QT += core |
注意: 此類的所有函數 可重入 .
| QCache (int maxCost = 100) | |
| ~QCache () | |
| void | clear () |
| bool | contains (const Key & key ) const |
| int | count () const |
| bool | insert (const Key & key , T * object , int cost = 1) |
| bool | isEmpty () const |
| QList<Key> | keys () const |
| int | maxCost () const |
| T * | object (const Key & key ) const |
| bool | remove (const Key & key ) |
| void | setMaxCost (int cost ) |
| int | size () const |
| T * | take (const Key & key ) |
| int | totalCost () const |
| T * | operator[] (const Key & key ) const |
QCache<Key, T> 定義存儲 Key 類型鍵關聯的 T 類型對象的緩存。例如,這裏是存儲整數鍵關聯的 Employee 類型對象的緩存定義:
QCache<int, Employee> cache;
這裏是如何將對象插入緩存:
Employee *employee = new Employee; employee->setId(37); employee->setName("Richard Schmit"); ... cache.insert(employee->id(), employee);
使用 QCache 優於某些其它基於鍵的數據結構 (譬如 QMap or QHash ),QCache 自動獲取插入緩存中對象的所有權,並刪除它們以便為新對象騰齣空間,若有必要。在將對象插入緩存時,可以指定 cost ,應該與對象所占用的內存量有一些近似關係。當所有對象的開銷之和 ( totalCost ()) 超過緩存限製 ( maxCost ()),QCache 開始刪除緩存中的對象以保持在限製之下,從最近訪問較少的對象開始。
默認情況下,QCache 的 maxCost () 為 100。可以在 QCache 構造函數中指定不同值:
QCache<int, MyDataStructure> cache(5000);
每次調用 insert (),可以將開銷指定作為第 3 自變量 (在鍵和指嚮要插入對象的指針之後)。調用後,插入對象歸 QCache 所有,QCache 可以隨時刪除它以便為其它對象騰齣空間。
要在緩存中查找對象,使用
object
() 或 operator[]()。此函數通過鍵查找對象,並返迴指嚮緩存對象 (由緩存擁有) 的指針或
nullptr
.
若想要從緩存移除特定鍵對象,調用 remove ()。這還會刪除對象。若想要從緩存中移除對象而不被 QCache 刪除,使用 take ().
另請參閱 QPixmapCache , QHash ,和 QMap .
Constructs a cache whose contents will never have a total cost greater than maxCost .
銷毀緩存。刪除緩存中的所有對象。
刪除緩存中的所有對象。
返迴
true
若緩存包含的對象關聯鍵
key
;否則返迴
false
.
如同 size ().
插入 object into the cache with key key and associated cost cost . Any object with the same key already in the cache will be removed.
After this call, object is owned by the QCache and may be deleted at any time. In particular, if cost 大於 maxCost (), the object will be deleted immediately.
函數返迴
true
若對象被插入緩存;否則它返迴
false
.
返迴
true
若緩存不包含對象;否則返迴
false
.
另請參閱 size ().
返迴緩存中的鍵列錶。
返迴緩存的最大允許總開銷。
另請參閱 setMaxCost () 和 totalCost ().
返迴的對象關聯鍵
key
,或
nullptr
若鍵未存在於緩存中。
警告: 返迴的對象歸 QCache 且可以在任何時候被刪除。
刪除的對象關聯鍵
key
。返迴
true
若對象在緩存中被找到;否則返迴
false
.
Sets the maximum allowed total cost of the cache to cost . If the current total cost is greater than cost , some objects are deleted immediately.
另請參閱 maxCost () 和 totalCost ().
返迴緩存中的對象數。
另請參閱 isEmpty ().
Takes the object associated with key key out of the cache without deleting it. Returns a pointer to the object taken out, or 0 if the key does not exist in the cache.
返迴對象的所有權被傳遞給調用者。
另請參閱 remove ().
返迴緩存中對象的總開銷。
此值通常低於 maxCost (),但 QCache makes an exception for Qt's 隱式共享 classes. If a cached object shares its internal data with another instance, QCache may keep the object lying around, possibly contributing to making totalCost() larger than maxCost ().
另請參閱 setMaxCost ().
返迴的對象關聯鍵
key
,或
nullptr
若鍵未存在於緩存中。
這如同 object ().
警告: 返迴的對象歸 QCache 且可以在任何時候被刪除。