当前位置: 首页 > news >正文

Memory should not be managed manually(Code Smell)

If you manage memory manually, it’s your responsibility to delete all memory created with new, and to make sure it’s delete d once and only once. Ensuring this is done is error-prone, especially when your function can have early exit points.

Fortunately, the C++ language provides tools that automatically manage memory for you. Using them systematically makes the code simpler and more robust without sacrificing performance.

This rule raises an issue when you use:

  • new - you should prefer a factory function that returns a smart pointer, such as std::make_unique or, if shared ownership is required, std::make_shared,
  • new[] - you should prefer a container class, such as std::vector,
  • delete or delete[] - if you followed the previous advice, there is no need to manually release memory.

If your compiler does not support make_unique, it’s easy to write your own:

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

Noncompliant Code Example

void f() {
  auto c = new Circle(0, 0, 5);
  c->draw();
  delete c;
}

Compliant Solution

void f() {
  auto c = make_unique<Circle>(0, 0, 5);
  c->draw();
  unique_ptr<Circle> c2{new Circle(0, 0, 5)}; // Clumsy, but still compliant by exception
}

Exceptions

If the result of a new is immediately passed as an argument to a function, we assume that the function takes ownership of the newly created object, and won’t raise an issue.

See

  • C++ Core Guidelines R.11 - Avoid calling new and delete explicitly
  • C++ Core Guidelines C.149 - Use unique_ptr or shared_ptr to avoid forgetting to delete objects created using new

 

相关文章:

  • macOS常用网络管理配置命令
  • 【第22节】C++设计模式(行为模式)-Iterator(迭代器)模式
  • 关于webpack的文件打包分割,并防止js文件缓存
  • 系统设计面试总结:4、单点登录SSO的概念、优势、OAuth2.0、具体实现(含时序图和跨域登录/登出的解决方案)
  • 如何在后端服务发布过程中使用蓝绿部署
  • AI资产管理系统与ERP对接API规范 v2.3
  • 小程序中下载文件 Vue3 写法
  • Linux(Centos 7.6)命令详解:vim
  • bert模型笔记
  • vim基本操作及常用命令
  • 【PLL】分频器:其他拓扑
  • Linux 进程管理
  • 大白话html语义化标签优势与应用场景
  • git如何解除远程仓库 改变远程仓库地址
  • Elasticsearch为索引设置自动时间戳,ES自动时间戳
  • 杂项知识笔记搜集
  • 【由技及道】量子跃迁部署术:docker+jenkins+Harbor+SSH的十一维交付矩阵【人工智障AI2077的开发日志011】
  • Java算法语法学习 美丽子集的数目 - 力扣 Map接口
  • 2025软件测试面试八股文(含答案+文档)
  • 传输协议优化的博弈三角
  • 网站建设滕州信息港/seo自媒体运营技巧
  • 怎么做网站文字图片/西安关键词排名软件
  • 适合做网站的图片/重庆快速排名优化
  • 百度建站系统/搜索引擎排名2021
  • 思勤传媒网站建设公司/精品成品网站入口
  • seo自己做网站吗/电子商务培训