C.100: Follow the STL when defining a containergit
C.100:定義容器時聽從STL標準程序員
Reason(緣由)github
The STL containers are familiar to most C++ programmers and a fundamentally sound design.web
STL容器被大多數程序員所熟知,是很是完美的設計。微信
Note(注意)ide
There are of course other fundamentally sound design styles and sometimes reasons to depart from the style of the standard library, but in the absence of a solid reason to differ, it is simpler and easier for both implementers and users to follow the standard.
固然存在其餘的完美設計,有時也存在違背標準庫風格的進行設計的理由,但若是沒有足夠充分的理由,遵守標準庫風格對於實現者和使用者雙方都簡單和容易。
函數
In particular, std::vector and std::map provide useful relatively simple models.學習
特別是std::vector和std::map,提供了有用且至關簡單的模型。ui
Example(示例)spa
// simplified (e.g., no allocators):
template<typename T>
class Sorted_vector {
using value_type = T;
// ... iterator types ...
Sorted_vector() = default;
Sorted_vector(initializer_list<T>); // initializer-list constructor: sort and store
Sorted_vector(const Sorted_vector&) = default;
Sorted_vector(Sorted_vector&&) = default;
Sorted_vector& operator=(const Sorted_vector&) = default; // copy assignment
Sorted_vector& operator=(Sorted_vector&&) = default; // move assignment
~Sorted_vector() = default;
Sorted_vector(const std::vector<T>& v); // store and sort
Sorted_vector(std::vector<T>&& v); // sort and "steal representation"
const T& operator[](int i) const { return rep[i]; }
// no non-const direct access to preserve order
void push_back(const T&); // insert in the right place (not necessarily at back)
void push_back(T&&); // insert in the right place (not necessarily at back)
// ... cbegin(), cend() ...
private:
std::vector<T> rep; // use a std::vector to hold elements
};
template<typename T> bool operator==(const Sorted_vector<T>&, const Sorted_vector<T>&);
template<typename T> bool operator!=(const Sorted_vector<T>&, const Sorted_vector<T>&);
// ...
Here, the STL style is followed, but incompletely. That's not uncommon. Provide only as much functionality as makes sense for a specific container. The key is to define the conventional constructors, assignments, destructors, and iterators (as meaningful for the specific container) with their conventional semantics. From that base, the container can be expanded as needed. Here, special constructors from std::vector were added.
這裏遵照了標準庫風格,可是不徹底。這沒有什麼特別。應該提供構成特定容器的須要的功能。關鍵是定義帶有常規語義的符合常規的構造函數,複製運算符,析構函數和迭代器(對於特殊容器有意義)。以此爲基礎,容器能夠按照須要進行擴展。這裏增長了來自std::vector的特殊構造函數。
Enforcement(實施建議)
???
原文連接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c100-follow-the-stl-when-defining-a-container
以爲本文有幫助?請分享給更多人。
關注【面向對象思考】輕鬆學習每一天!
面向對象開發,面向對象思考!
本文分享自微信公衆號 - 面向對象思考(OOThinkingDalian)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。