Double check code

is there any problem with this, what's wrong?

string* greeting() {
string s(“Hi!”);
return &s;
}

Is it that string doesn't have type?
Why are you returning a pointer? s goes out of scope at the end of the function and is destroyed. Also it's generally better to use std::string, rather than just string.
How would it be work tho?
Or just
1
2
3
4
std::string greeting()
{
return std::string("Hi!");
}

However this seems like a pointless function, so without knowing why are doing this or in what context it's being used, it's difficult to help more.
closed account (48bpfSEw)
why return a pointer and not a reference to?

1
2
3
4
5
string& greeting() 
{
    static string s(“Hi!”);
    return s;
}
Topic archived. No new replies allowed.