


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源创计划”,欢迎正在阅读的你也加入,一块儿分享。