#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;
}
RésultatPourquoi y a-t-il une différence entre la valeur avant le retour et la valeur après le retour?
before value = [bc]
after value = [**gabage value**]
Est-ce que la valeur de la mémoire disparaît à la fin de la fonction? Je ne comprends pas pourquoi ces valeurs changent.
Voir ici: https://stackoverflow.com/questions/6456359/what-is-stdstringc-str-lifetime – meowgoesthedog