Johan Kotlinski
Johan Kotlinski

Reputation: 25759

What happens first, implicit conversion to return value or destruction of local variable?

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

Answers (1)

Ivaylo Strandjev
Ivaylo Strandjev

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

Related Questions