C++核心準(zhǔn)則編譯邊學(xué)-F.22 使用T*或onwer指明唯一對(duì)象

F.22: Use T* or owner to designate a single object(使用T*或owner指明唯一對(duì)象)
Reason(原因)
Readability: it makes the meaning of a plain pointer clear. Enables significant tool support.
可讀性:這可以讓裸指針的含義更明確。使重要的工具支持有效。
譯者注
譯者注:owner
Note(注意)
In traditional C and C++ code, plain T* is used for many weakly-related purposes, such as:
在傳統(tǒng)的C和C++代碼中,裸指針用于很多沒有什么關(guān)系的目的,例如:
Identify a (single) object (not to be deleted by this function)
表示一個(gè)(單一)對(duì)象(不會(huì)被本函數(shù)刪除)
Point to an object allocated on the free store (and delete it later)
指向一個(gè)從自由存儲(chǔ)上獲取的對(duì)象(以后會(huì)刪除)
Hold the
nullptr持有nullptr
Identify a C-style string (zero-terminated array of characters)
表示一個(gè)C風(fēng)格字符串(以0結(jié)尾的字符數(shù)組)
Identify an array with a length specified separately
表示一個(gè)數(shù)組,長(zhǎng)度被另外定義
Identify a location in an array
表示數(shù)組的首地址
This makes it hard to understand what the code does and is supposed to do. It complicates checking and tool support.
這樣做的結(jié)果是很難理解代碼在做什么和被預(yù)期做什么。無(wú)論是檢查還是工具支持都會(huì)復(fù)雜。
Example(示例)
void use(int* p, int n, char* s, int* q){p[n - 1] = 666; // Bad: we don't know if p points to n elements;// assume it does not or use spancout << s; // Bad: we don't know if that s points to a zero-terminated array of char;// assume it does not or use zstringdelete q; // Bad: we don't know if *q is allocated on the free store;// assume it does not or use owner}
譯者注:這可能是我們每天都能見到的指針用法,很難看出它們到底是前面提供的那種用法。
better(稍好)
void use2(span<int> p, zstring s, owner<int*> q){p[p.size() - 1] = 666; // OK, a range error can be caughtcout << s; // OKdelete q; // OK}
Note(注意)
owner represents ownership, zstring represents a C-style string.
owner
Also: Assume that a T* obtained from a smart pointer to T (e.g., unique_ptr) points to a single element.
參考:假定T*是從指向T的智能指針(例如unique_prt
See also: Support library
參考:支持庫(kù)。
See also: Do not pass an array as a single pointer
參考:不要使用單一指針傳遞數(shù)組
Enforcement(實(shí)施建議)
(Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
(簡(jiǎn)單)((邊界))警告所有針對(duì)指針表達(dá)式,并得到指針類型結(jié)果的算數(shù)操作。
