溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++中為什么使用not_null<T>表明空是無效值

發(fā)布時間:2021-11-24 11:50:57 來源:億速云 閱讀:289 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要講解了“C++中為什么使用not_null<T>表明空是無效值”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“C++中為什么使用not_null<T>表明空是無效值”吧!

Reason(原因)

清晰性。一個使用not_null<T>參數(shù)的函數(shù)可以明確地表明:如果有必要,調(diào)用者有責(zé)任進(jìn)行空指針檢查。類似的,返回not_null<T>的函數(shù)向調(diào)用者清晰的表明了不需要進(jìn)行nullptr的檢查。

Example(示例)

not_null<T*> makes it obvious to a reader (human or machine) that a test for nullptr is not necessary before dereference. Additionally, when debugging, owner<T*> and not_null<T> can be instrumented to check for correctness.

not_null<T*>向讀者(人或機(jī)器)表明不需要在解引用之前進(jìn)行nullptr檢查。另外,在調(diào)試的時候,onwer<T*>和not_null<T>可用于正確性檢查。

Consider:(考慮以下代碼:)

int length(Record* p);

When I call length(p) should I check if p is nullptr first? Should the implementation of length() check if p is nullptr?

在調(diào)用length(p)的時候需要首先檢查p是否是nullptr嗎?實現(xiàn)length()的時候應(yīng)該檢查p是否為nullptr嗎?

// it is the caller's job to make sure p != nullptrint length(not_null<Record*> p);
// the implementor of length() must assume that p == nullptr is possibleint length(Record* p);  

not_null<T*>被假定不會是nullptr;T*可能是nullptr;兩者在內(nèi)存上都表現(xiàn)為T*(因此不會付出額外的代價)。

Note(注意)

not_null is not just for built-in pointers. It works for unique_ptr, shared_ptr, and other pointer-like types.

not_null不止適用于內(nèi)置指針。它也適用于unique_ptr和shared_ptr以及其他類似指針的類型。

Enforcement(實施建議)

  • (Simple) Warn if a raw pointer is dereferenced without being tested against nullptr (or equivalent) within a function, suggest it is declared not_null instead.

    (簡單)處于某個函數(shù)中的裸指針如果沒有進(jìn)行nullptr(或等價的)檢查就解引用,則報警。建議定義為not_null。

  • (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against nullptr (or equivalent) within the function and sometimes is not.

    (簡單)如果一個裸指針在解引用之前,有時會進(jìn)行防空檢查有時又不檢查,報錯。

  • (Simple) Warn if a not_null pointer is tested against nullptr within a function.

    (簡單)如果not_null指針在函數(shù)內(nèi)部進(jìn)行了防空判斷,報警。

感謝各位的閱讀,以上就是“C++中為什么使用not_null<T>表明空是無效值”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對C++中為什么使用not_null<T>表明空是無效值這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI