Is it possible to do this
std::string str(const char* s)
{
return std::string(s);
}
int main() {
char* strz = (char*)str("asd").c_str();
}
Instead of:
int main(){
std::string temp = str("asd");
char* strz = (char*)temp.c_str();
}
I know it should be const char* strz but I need it only within block of code(and without new/delete). After returning string from method it look for reference(if cant find it, deletes string) and then calls c_str(). I have a lot of char’s(independent from me) and I could use second solution but it takes too much code.
If you use your second option –
You’re possibly running into undefined behavior. It’s illegal to modify the contents of
strz. You’ll have to usestrcpyto get a mutable array ofchar‘s. Your first isn’t any better either, moreover, it’s redundant, since you can directly usestring‘s constructor.Anyway, to get a
char*from astringyou can do:You’ll have to
delete[]the memory yourself when you’re done with it.