C++避坑指南-作用域失效
问题场景
一般是局部变量出作用域后继续访问, 导致指针指向一块已经无效的内存
听起来比较简单,但在实际工程应用中,这类情况还是经常出现的,而且一般需要借助asan等内存异常检测工具才能比较快的排查到
示例代码
#include <iostream>
#include <string>
using namespace std;
class Speaker
{
public:
void Speak()
{
cout << "My name is "<<name <<", and I am from " << country << endl;
}
std::string name;
std::string country;
};
Speaker* MakeSpeaker()
{
Speaker s;
s.name = "Wang Liang";
s.country = "China";
return &s;
}
int main(int argc, char* argv[])
{
Speaker* s = MakeSpeaker();
s->Speak();
return 0;
};
程序运行coredump:
解决方法:
在工程开发中需要对各种对象的生命周期分析清楚,是贯穿请求处理的整个生命周期,还是临时对象,对于内存使用来说,越早释放越合理,但需要注意避免作用域失效后访问到