前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​讨论:切勿让指针的生命周期超出其指向的对象

C++核心准则​讨论:切勿让指针的生命周期超出其指向的对象

作者头像
面向对象思考
发布2020-12-31 14:54:25
6600
发布2020-12-31 14:54:25
举报

Discussion: Never let a pointer outlive the object it points to

讨论:切勿让指针的生命周期超出其指向的对象

Reason(原因)

To avoid extremely hard-to-find errors. Dereferencing such a pointer is undefined behavior and could lead to violations of the type system.

避免极难发现的错误。 防止引用此类指针未定义、并可能导致破坏类型安全系统的行为。

Example(例)

代码语言:javascript
复制
string* bad()   // really bad
{
    vector<string> v = { "This", "will", "cause", "trouble", "!" };
    // leaking a pointer into a destroyed member of a destroyed object (v)
    return &v[0];
}

void use()
{
    string* p = bad();
    vector<int> xx = {7, 8, 9};
    // undefined behavior: x might not be the string "This"
    string x = *p;
    // undefined behavior: we don't know what (if anything) is allocated a location p
    *p = "Evil!";
}

The strings of v are destroyed upon exit from bad() and so is v itself. The returned pointer points to unallocated memory on the free store. This memory (pointed into by p) might have been reallocated by the time *p is executed. There might be no string to read and a write through p could easily corrupt objects of unrelated types.

v的字符串s在bad退出时被销毁,v本身也被销毁。返回的指针指向自由存储中的未分配内存。在执行* p时,该内存(由p指向)可能已经被重新分配。可能没有要读取的字符串,并且通过p进行的写入很容易损坏无关类型的对象。

Enforcement(实施建议)

Most compilers already warn about simple cases and have the information to do more. Consider any pointer returned from a function suspect. Use containers, resource handles, and views (e.g., span known not to be resource handles) to lower the number of cases to be examined. For starters, consider every class with a destructor as resource handle.

大多数编译器已经可以警告一些简单的情况,并提供更多信息。考察从函数返回的任何可疑指针。使用容器,资源句柄和视图(例如,span已知不是资源句柄)来减少要检查的需求量。对于初学者,请将具有析构函数的每个类视为资源句柄。

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#discussion-never-let-a-pointer-outlive-the-object-it-points-to

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

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

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

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

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