前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.62:保证拷贝赋值对自我赋值安全

C++核心准则C.62:保证拷贝赋值对自我赋值安全

作者头像
面向对象思考
发布2020-03-25 16:15:30
3760
发布2020-03-25 16:15:30
举报
文章被收录于专栏:C++核心准则原文翻译

C.62: Make copy assignment safe for self-assignment C.62:保证拷贝赋值对自我赋值安全

Reason(原因)

If x = x changes the value of x, people will be surprised and bad errors will occur (often including leaks).

如果x=x改变了x的值,人们会觉得很奇怪,同时也会发生很不好的错误。(通常会包含泄露)

Example(示例)

The standard-library containers handle self-assignment elegantly and efficiently:

标准库容器处理自我赋值的方式优雅且高效:

代码语言:javascript
复制
std::vector<int> v = {3, 1, 4, 1, 5, 9};
v = v;
// the value of v is still {3, 1, 4, 1, 5, 9}

Note(注意)

The default assignment generated from members that handle self-assignment correctly handles self-assignment.

产生于正确处理了自我赋值的成员的默认的赋值操作会处理自我赋值问题。

代码语言:javascript
复制
struct Bar {
    vector<pair<int, int>> v;
    map<string, int> m;
    string s;
};

Bar b;
// ...
b = b;   // correct and efficient

Note(注意)

You can handle self-assignment by explicitly testing for self-assignment, but often it is faster and more elegant to cope without such a test (e.g., using swap).

你可以通过明确地对自我赋值进行检查的方式防止自我赋值,但是通常不使用上述检查的处理方式(例如使用swap)的方式更快,更优雅。

代码语言:javascript
复制
class Foo {
    string s;
    int i;
public:
    Foo& operator=(const Foo& a);
    // ...
};

Foo& Foo::operator=(const Foo& a)   // OK, but there is a cost
{
    if (this == &a) return *this;
    s = a.s;
    i = a.i;
    return *this;
}

This is obviously safe and apparently efficient. However, what if we do one self-assignment per million assignments? That's about a million redundant tests (but since the answer is essentially always the same, the computer's branch predictor will guess right essentially every time). Consider:

这种做法看起来安全并且高效。但是如果在一百万次赋值中只发生一次自我赋值的情况下会怎么样呢?大概有一百万次多余的检查(但是由于本质上结果总是一样的,计算机的分支预测会每次都猜对)。考虑下面的代码:

代码语言:javascript
复制
Foo& Foo::operator=(const Foo& a)   // simpler, and probably much better
{
    s = a.s;
    i = a.i;
    return *this;
}

std::string is safe for self-assignment and so are int. All the cost is carried by the (rare) case of self-assignment.

std::string对自我赋值安全,int也是。所有的代价都来自(极少)发生的自我赋值。

Enforcement(实施建议)

(Simple) Assignment operators should not contain the pattern if (this == &a) return *this; ???

(简单)赋值运算符不应该包含以下的检查:if (this == &a) return *this;


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

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-01-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档