Originally Posted by
justAlamer
then why the return type of c_str() is const char * ?
Because you are not supposed to modify that string.
Originally Posted by
justAlamer
and what is the right way to take in such situations?
for example if I don't have control over the caller function
If you want to keep the return type as a pointer, you may have little choice but to write:
Code:
const char* f()
{
string s("whatever");
// ...
char* ret = new char[s.size() + 1];
std::strcpy(ret, s.c_str());
return ret;
}
On the other hand, there is also the option of:
Code:
std::string f()
{
std::string s("whatever");
// ...
return s;
}
or the use of an in/out parameter:
Code:
void f(std::string& s)
{
s = "whatever";
// ...
}
Originally Posted by
justAlamer
so if I dynamically create a string object (string *s = new string("hello")) and if I free the memory pointed to by the pointer returned by s->c_str() do I also have to free/delete "s"?
You are not allowed to directly free the memory pointed to by the pointer returned by s->c_str(). What you can do in such a case is to delete s, or a copy of s... but why bother with manual memory management when you don't have to?