C++核心准则C.100:定义容器时遵从STL标准
共 2643字,需浏览 6分钟
·
2020-01-25 23:21
C.100: Follow the STL when defining a container
C.100:定义容器时遵从STL标准
Reason(原因)
The STL containers are familiar to most C++ programmers and a fundamentally sound design.
STL容器被大多数程序员所熟知,是非常完美的设计。
Note(注意)
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,提供了有用且相当简单的模型。
Example(示例)
// simplified (e.g., no allocators):
template
class Sorted_vector {
using value_type = T;
// ... iterator types ...
Sorted_vector() = default;
Sorted_vector(initializer_list); // 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& v); // store and sort
Sorted_vector(std::vector&& 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::vectorrep; // use a std::vector to hold elements
};
templatebool operator==(const Sorted_vector &, const Sorted_vector &);
templatebool operator!=(const Sorted_vector &, const Sorted_vector &);
// ...
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
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!