溫馨提示×

溫馨提示×

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

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

C++怎么用not_null定義不能為空的指針

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

本篇內(nèi)容主要講解“C++怎么用not_null定義不能為空的指針”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“C++怎么用not_null定義不能為空的指針”吧!

I.12: Declare a pointer that must not be null as not_null( 用not_null定義不能為空的指針

Reason(原因)

To help avoid dereferencing nullptr errors. To improve performance by avoiding redundant checks for nullptr.

為了防止解引用nullptr錯(cuò)誤。為了避免多余的空指針檢查以提高性能。

譯者注:解引用就是指針前面加*獲取內(nèi)容的操作。

Example(示例)

int length(const char* p);            // it is not clear whether length(nullptr) is valid
length(nullptr);                      // OK?
int length(not_null<const char*> p);  // better: we can assume that p cannot be nullptr
int length(const char* p);            // we must assume that p can be nullptr

By stating the intent in source, implementers and tools can provide better diagnostics, such as finding some classes of errors through static analysis, and perform optimizations, such as removing branches and null tests.

通過在代碼中說明目的,實(shí)現(xiàn)者和工具可以提供較好的診斷,例如通過靜態(tài)分析發(fā)現(xiàn)某些類型的錯(cuò)誤,執(zhí)行性能優(yōu)化,例如移除分支和空判斷。

譯者注:指的是上述代碼中使用not_null的情況。

Note(注意)

not_null is defined in the guidelines support library.

not_null在準(zhǔn)則支持庫中被定義。

譯者注:積極地使用準(zhǔn)則庫。

Note(注意)

The assumption that the pointer to char pointed to a C-style string (a zero-terminated string of characters) was still implicit, and a potential source of confusion and errors. Use czstring in preference to const char*.

指向字符的指針會(huì)指向一個(gè)C風(fēng)格的字符串(以0結(jié)尾的字符串)這樣一個(gè)假設(shè)還是沒有說清楚,這會(huì)成為不確定性和錯(cuò)誤的來源。在引用const char*時(shí)使用czstring。

// we can assume that p cannot be nullptr// we can assume that p points to a zero-terminated array of charactersint length(not_null<zstring> p);

Note: length() is, of course, std::strlen() in disguise.

注意:length()當(dāng)然是偽裝的std::strlen。

Enforcement(實(shí)施建議)

  • (Simple) ((Foundation)) If a function checks a pointer parameter against nullptr before access, on all control-flow paths, then warn it should be declared not_null.

    (簡單)((基礎(chǔ)))如果一個(gè)函數(shù)在使用指針參數(shù)之前在所有控制流路徑上進(jìn)行空檢查,那么發(fā)出應(yīng)該參數(shù)被聲明為not_null的警告信息。

  • (Complex) If a function with pointer return value ensures it is not nullptr on all return paths, then warn the return type should be declared not_null.

    (復(fù)雜)如果一個(gè)指針類型(返回值)函數(shù)在它的所有返回路徑上都確認(rèn)返回值不為空,那么發(fā)出返回值應(yīng)該被定義為not_null的警告信息。

到此,相信大家對(duì)“C++怎么用not_null定義不能為空的指針”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

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

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

c++
AI