string& f()
{
   string str = "name";
   return str;

I need to return a reference to a string,but i am confused how to return corectly from f(),any help ?

Recommended Answers

All 2 Replies

Local variables are destroyed when the function returns. If you need a reference, you also need a different place to store the string so that it has a longer lifetime.

If you need a reference, I recommend passing into the method by reference as so

void f(string &myString)
{
   myString = "name";
}

As rpfd stated, local variables are destroyed when they go out of scope and returning a pointer created in the method is a bad practise (the programmer of a future library may not know they need to delete the pointer, memory leak occurs).

As you only need a reference, pass the string in by reference and any changes made inside the method will be reflected in the original object.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.