Reputation: 1513
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?
Upvotes: 3
Views: 180
Reputation: 8492
The variable s
, will go out of scope once control exits that block, at which point its destructor will be called.
When is an object "out of scope"?
Upvotes: 1
Reputation:
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?
Upvotes: 8
Reputation: 3324
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.
Upvotes: 3
Reputation: 63471
It will store a dangling pointer that you must not access. It may contain the string "something"
or it may not. It doesn't matter, because accessing it is undefined behaviour, and should be avoided completely.
If you want to copy the string do this:
c = strdup( c.c_str() );
And don't forget to free(c)
in ~Class1()
Beware that if you call func1
twice, you will leak memory. You probably want to initialise c
to NULL
in the constructor, and call free(c)
before reassigning it in func1
.
Surely a better approach is to store a std::string
instead of a char*
, which manages memory properly for you.
Upvotes: 1