C++核心准则C.100:定义容器时遵从STL标准‍

C++核心准则C.100:定义容器时遵从STL标准‍

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(示例)‍

<code>//simplified(e.g.,noallocators):template<typenamet>  classSorted_vector{  usingvalue_type=T;//...iteratortypes...  Sorted_vector()=default;  Sorted_vector(initializer_list);//initializer-listconstructor:sortandstore  Sorted_vector(constSorted_vector&)=default;  Sorted_vector(Sorted_vector&&)=default;  Sorted_vector&operator=(constSorted_vector&)=default;//copyassignment  Sorted_vector&operator=(Sorted_vector&&)=default;//moveassignment  ~Sorted_vector()=default; Sorted_vector(conststd::vector&v);//storeandsort Sorted_vector(std::vector&&v);//sortand"stealrepresentation" constT&operator[](inti)const{returnrep[i];                        }//nonon-constdirectaccesstopreserveorder voidpush_back(constT&);//insertintherightplace(notnecessarilyatback) voidpush_back(T&&);//insertintherightplace(notnecessarilyatback)//...cbegin(),cend()...private:std::vectorrep;//useastd::vectortoholdelements};template<typenamet>booloperator==(constSorted_vector&,constSorted_vector&);template<typenamet>booloperator!=(constSorted_vector&,constSorted_vector 
&);//...
/<typenamet>
/<typenamet>
/<typenamet>/<code>

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


觉得本文有帮助?请分享给更多人。

更多精彩文章请关注微信公众号【面向对象思考】!

面向对象开发,面向对象思考!


分享到:


相關文章: