2017-07-20 55 views
0
#include <iostream> 
#include <cstring> 

using namespace std; 

const char * substringAfterLast(const char * str, const char * separator) 
{ 
    if (str == NULL) { 
     return NULL; 
    } 
    else if (str[0] == '\0' || separator == NULL || separator[0] == '\0') { 
     return ""; 
    } 
    else { 
     string ret(str); 
     size_t found = ret.find_last_of(separator); 
     ret = ret.substr(found + 1); 
     cout << "before value = [" << const_cast<char*>(ret.c_str()) << "]" << endl; 
     return const_cast<char*>(ret.c_str()); 
    } 
} 

int main(void) 
{ 
    cout << "after value = [" << substringAfterLast("abc", "a") << "]" << endl;  
} 

结果为什么回报前的价值与回报后的价值有差异?

before value = [bc] 
after value = [**gabage value**] 

是否值从内存在函数的结束而消失? 我不明白为什么这些值会改变。

+0

请看这里:https://stackoverflow.com/questions/6456359/what-is-stdstringc-str-lifetime – meowgoesthedog

回答

1

您从c_str()获取的指针为严格为 a const char*类型。此外,它仅在支持字符串ret的生命周期的较早时刻或以任何方式修改ret时才有效。

任何不符合这些原则的代码(如您的)的行为是undefined