C++核心準則C102-109:容器的基本要求

火歐珀
C.102: Give a container move operations
C.102:為容器實現(xiàn)移動操作?

Reason(原因)
Containers tend to get large; without a move constructor and a copy constructor an object can be expensive to move around, thus tempting people to pass pointers to it around and getting into resource management problems.
容器會變得越來越大;如果對象沒有移動構造函數(shù)和拷貝構造函數(shù),移動它的成本就會很高,其結果就是導致人們更愿意傳遞指向?qū)ο蟮闹羔槒亩鹳Y源管理方面的問題。

Example(示例)
Sorted_vector?read_sorted(istream&?is)
{
????vector?v;
????cin?>>?v;???//?assume?we?have?a?read?operation?for?vectors
????Sorted_vector?sv?=?v;??//?sorts
????return?sv;
}
A user can reasonably assume that returning a standard-like container is cheap.
用戶可以合理地假設返回和標準庫類似的容器是低成本的。

Enforcement(實施建議)
???
C.103: Give a container an initializer list constructor
C.103:為容器實現(xiàn)一個初始化類別形式的構造函數(shù)?

Reason(原因)
People expect to be able to initialize a container with a set of values. Familiarity.
人們希望可以通過一組值來初始化容易。這是友好性方面的考慮。

Example(示例)
Sorted_vector?sv?{1,?3,?-1,?7,?0,?0};?
//?Sorted_vector?sorts?elements?as?needed

Enforcement(實施建議)
???
C.104: Give a container a default constructor that sets it to empty
C.104:為容器實現(xiàn)一個將容器初始化為空的默認構造函數(shù)?

Reason(原因)
To make it?Regular.
保持容器的常規(guī)性。

Example(示例)
vector>?vs(100);????//?100?Sorted_sequences?each?with?the?value?""

Enforcement(實施建議)
???
C.109: If a resource handle has pointer semantics, provide?*?and?->
C.109:如果資源句柄包含指針語義,提供*和->運算符

Reason(原因)
That's what is expected from pointers. Familiarity.
這是來自指針類型的期望。友好型方面的考慮。

Example(示例)
???

Enforcement(實施建議)
???

原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c102-give-a-container-move-operations
覺得本文有幫助?請分享給更多人。
關注【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/p>
