随笔分类 -  C++避坑指南

摘要:隐式类型转换介绍 c++编译时会在不同类型间进行自动转换, 因此使用不同数据类型进行比较、赋值等操作时, 可能不会报错,但可能因为忽略这些隐式类型转换而产生问题,而且不易排查 分场景代码示例 int负数值隐式转换为unsigned int 如下示例代码: #include <iostream> us 阅读全文
posted @ 2022-07-24 11:30 飞天赤狐 阅读(78) 评论(0) 推荐(0) 编辑
摘要:问题场景 在一段处理开始时new一个对象, 进行对象的构造或其他处理, 最后返回对象的指针, 但存在对象构造时check不合法的情况,这种情况下返回nullptr, 为避免内存泄露需要在返回nullptr的分支进行delete处理,由于分支可能较多,这里可能会遗漏delete,另外每个分支重复的加d 阅读全文
posted @ 2022-07-23 10:47 飞天赤狐 阅读(30) 评论(0) 推荐(0) 编辑
摘要:问题场景 有些不应该被复制的对象, 被复制了, 复制前后的对象都持有同一指针成员, 析构时重复释放造成内存异常,程序coredump 示例代码 #include <iostream> #include <string> using namespace std; class Person { publ 阅读全文
posted @ 2022-07-10 22:38 飞天赤狐 阅读(69) 评论(0) 推荐(0) 编辑
摘要:问题场景 在访问数组时没有判断数组size, 导致访问的索引号超过了数组size产生访问越界,程序出现异常行为 示例代码 实际情况比较多, 我们来展开说明下 原生数组访问越界 #include <iostream> using namespace std; void ArrayOut() { int 阅读全文
posted @ 2022-07-09 11:08 飞天赤狐 阅读(408) 评论(0) 推荐(0) 编辑
摘要:问题场景 一般是局部变量出作用域后继续访问, 导致指针指向一块已经无效的内存 听起来比较简单,但在实际工程应用中,这类情况还是经常出现的,而且一般需要借助asan等内存异常检测工具才能比较快的排查到 示例代码 #include <iostream> #include <string> using n 阅读全文
posted @ 2022-07-09 10:24 飞天赤狐 阅读(49) 评论(0) 推荐(0) 编辑
摘要:编写除法计算时,一定要注意判断除数是否为0 这条比较简单 如下: #include <iostream> using namespace std; int main(int argc, char* argv[]) { int d = 0; float result = 100/d; cout << 阅读全文
posted @ 2022-07-09 10:03 飞天赤狐 阅读(261) 评论(0) 推荐(0) 编辑
摘要:问题场景: 以vector为例,有时候我们会把原始数据列表作为vector数组,同时把需要排序或其他处理的数组使用指向原始vector的迭代器数组 示例代码: #include <iostream> #include <vector> #include <algorithm> using names 阅读全文
posted @ 2022-06-26 20:52 飞天赤狐 阅读(19) 评论(0) 推荐(0) 编辑
摘要:错误写法 循环内直接erase #include <iostream> #include <vector> #include <string> using namespace std; int main(int argc, char* argv[]) { vector<string> nameLis 阅读全文
posted @ 2022-06-23 07:28 飞天赤狐 阅读(127) 评论(0) 推荐(0) 编辑

点击右上角即可分享
微信分享提示