C++核心准则C102-109:容器的基本要求

面向对象思考

共 1625字,需浏览 4分钟

 · 2020-01-27

68ff0117a9dd8a2113b6d9f6147ed9e2.webp

火欧珀

C.102: Give a container move operations

C.102:为容器实现移动操作‍


a8d6c7c9632927ead7da343bee533de3.webp

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.

容器会变得越来越大;如果对象没有移动构造函数和拷贝构造函数,移动它的成本就会很高,其结果就是导致人们更愿意传递指向对象的指针从而引起资源管理方面的问题。


a8d6c7c9632927ead7da343bee533de3.webp

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.

用户可以合理地假设返回和标准库类似的容器是低成本的。


a8d6c7c9632927ead7da343bee533de3.webp

Enforcement(实施建议)

???


C.103: Give a container an initializer list constructor

C.103:为容器实现一个初始化类别形式的构造函数‍


a8d6c7c9632927ead7da343bee533de3.webp

Reason(原因)

People expect to be able to initialize a container with a set of values. Familiarity.

人们希望可以通过一组值来初始化容易。这是友好性方面的考虑。


a8d6c7c9632927ead7da343bee533de3.webp

Example(示例)

Sorted_vector sv {1, 3, -1, 7, 0, 0}; 
// Sorted_vector sorts elements as needed
a8d6c7c9632927ead7da343bee533de3.webp

Enforcement(实施建议)

???


C.104: Give a container a default constructor that sets it to empty

C.104:为容器实现一个将容器初始化为空的默认构造函数‍


a8d6c7c9632927ead7da343bee533de3.webp

Reason(原因)

To make it Regular.

保持容器的常规性。


a8d6c7c9632927ead7da343bee533de3.webp

Example(示例)

vector> vs(100);    // 100 Sorted_sequences each with the value ""
a8d6c7c9632927ead7da343bee533de3.webp

Enforcement(实施建议)

???


C.109: If a resource handle has pointer semantics, provide * and ->

C.109:如果资源句柄包含指针语义,提供*和->运算符

a8d6c7c9632927ead7da343bee533de3.webp

Reason(原因)

That's what is expected from pointers. Familiarity.

这是来自指针类型的期望。友好型方面的考虑。


a8d6c7c9632927ead7da343bee533de3.webp

Example(示例)

???
a8d6c7c9632927ead7da343bee533de3.webp

Enforcement(实施建议)

???


a8d6c7c9632927ead7da343bee533de3.webp

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c102-give-a-container-move-operations




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

关注【面向对象思考】轻松学习每一天!

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

浏览 4
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报