ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
##实战c++中的string系列--函数返回局部变量string(引用局部string,局部string的.c_str()函数) 当函数返回字符串的时候,我们可以定义返回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; } ~~~