Reputation: 25759
I just bumped into code like the following which looks fishy to me (details left out to protect the innocent):
std::string MakeString()
{
char buf[12] = { 0 };
return &buf[0];
}
Is this OK or unsafe? Is it guaranteed that std::string is created before buf goes out of scope?
Upvotes: 4
Views: 192
Reputation: 71009
What you have written is equivalent to:
std::string MakeString()
{
char buf[12] = { 0 };
return buf;
}
And it is always guaranteed that this code is safe. In fact this case is not much different from any function that returns a value by copy.
Upvotes: 6