I have got a quick question. I have the following code:
class Class1
{
Class1();
~Class1();
void func1();
private:
char* c;
}
void Class1::func1()
{
string s = "something";
this->c = s.c_str();
}
will c store "something" when func1() finishes?
No. It will invoke undefined behavior instead. (if you dereference the pointer, anyway.) Since s is a block-scope object with automatic storage duration, it is destroyed when the function returns, and that renders the pointer returned by .c_str() invalid.
Why not use an std::string member variable instead?
s is a local variable of type std::string in Class::func1. Once func1() finishes, the string s will go out of scope.
Any pointers you have with the address of s stored in them will become dangling pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With