C++核心准则C.11:让具体类型符合常规

共 1423字,需浏览 3分钟

 ·

2019-12-16 23:21



2721e8d9af539a80141f3306541f33af.webp

C.11: Make concrete types regular

C.11:让具体类型符合常规


Reason(原因)

Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use).

常规类型和非常规类型相比更容易理解和推测。理解和使用不符合常规的类型需要额外努力才行。


Example(示例)

struct Bundle {
string name;
vector vr;
};

bool operator==(const Bundle& a, const Bundle& b)
{
return a.name == b.name && a.vr == b.vr;
}

Bundle b1 { "my bundle", {r1, r2, r3}};
Bundle b2 = b1;
if (!(b1 == b2)) error("impossible!");
b2.name = "the other bundle";
if (b1 == b2) error("No!");

In particular, if a concrete type has an assignment also give it an equals operator so that a = b implies a == b.

通常情况下,如果具体类型包含赋值操作,同时应提供判断相等的操作。也就是说有a=b意味着也有a==b。


Note(注意)

Handles for resources that cannot be cloned, e.g., a scoped_lock for a mutex, resemble concrete types in that they most often are stack-allocated.

However, objects of such types typically cannot be copied (instead, they can usually be moved),so they can't be regular; instead, they tend to be semiregular.Often, such types are referred to as "move-only types".

管理不允许克隆的资源,例如用于管理mutex的scoped_lock,由于经常在堆栈上分配,因此看起来像具体类型。但是这类类型的对象通常不能被拷贝(它们通常被移动),因此它们不属于常规的范畴,而是趋向于半常规。这样的类型经常被成为“只移动类型”。


Enforcement(实施建议)

???


原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c11-make-concrete-types-regular




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

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

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


浏览 24
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

分享
举报