c++函数中返回的局部变量string(在外面引用局部string,局部string的.c_str()函数) 【转】
版权声明:
本文为博主学习过程中整理发布,如有侵权请告知
更新时间:
2017-10-23 16:21:38
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
c语言中很多函数都是先定义一个缓冲区变量然后传引用或指针进去,函数处理完后就把数据填充到那个缓冲区中,而我们用其它语言差不多都是直接传入函数然后接收返回值,并没有考虑那么多。最近使用c++过程中写函数时都是直接在函数里定义一个string局部变量然后直接返回,也没有考虑过这种情况有啥bug没有,于是到网上查到啦这个文章,描述的很清楚,记录下来
当函数返回字符串的时候,我们可以定义返回string和string&。
1写一个返回string引用的函数
std::string & TestStringReference() { std::string loal_str = "holy shit"; return loal_str; }
这个函数当然是错误的,编译器会提示我们:
返回局部变量或临时变量的地址: loal_str
即不能返回局部变量的引用。
2写一个返回string的函数(函数返回局部变量string的时候能不能被引用?)
std::string TestStringReference() { std::string strTest = "This is a test."; return strTest; }
那么对于上述函数的返回值可以被引用吗?
代码说话:
#include<iostream>#include<string>std::string TestStringReference() { std::string strTest = "This is a test."; return strTest; }int main() { std::string& strRefer = TestStringReference(); std::cout << "strRefer:" << strRefer << std::endl; return 0; }
代码 完美运行。
实际上返回的不是局部变量,而是编译器新构造的临时对象。
3返回string的函数直接调用.c_str()
上面说了,返回的“局部”string可以被引用的,那么返回的“局部”string直接调用.c_str()会有什么效果恩?
#include<iostream>#include<string>std::string TestStringC_STR() { std::string strTest = "This is a test."; return strTest; }int main() { const char *pc = TestStringC_STR().c_str(); std::cout << pc << std::endl; return 0; }
上面代码编译器不会报错!
但是等等,别高兴太早,看看输出结果,为空,不是我们期望的。
关键是,我们没有将TestStringC_STR()的结果赋给一个string对象就直接获取其指针了,这时,系统并不会为string调用拷贝构造函数或是赋值函数,返回的string仍然只是一个临时对象的状态,它会在完成对pc的赋值后被销毁,这时其内部的数据也不会存在了。
解决方法:先用一个string接收函数的返回值,然后再调用c_str()方法:
#include<iostream>#include<string>std::string TestStringC_STR() { std::string strTest = "This is a test."; return strTest; }int main() { std::string str1 = TestStringC_STR(); const char *pc = str1.c_str(); std::cout << pc << std::endl; return 0; }