You can't return a reference to a local variable from a function with c++. Although in c++0x this is possible.
Allocate the string on the heap and manually cleanup later:
If you cannot change the function's interface, then you will need to create it on the heap and then manually delete it after.
//Remember to free the address that getVal returns
const std::string& getVal(const std::string &key) {
std::string *retVal = new std::string();
... //build retVal string with += operator based on key
return *retVal;
}
Same solution but not manually:
Since the above will eventually lead to a memory leak if you forget to free it manually. I would recommend to wrap this call into a class and use RAII. I.e. in the constructor, call getVal and set a member of this class to point to it. In the destructor of your class you would delete it.
Why the code you gave with shared_ptr does not work:
shared_ptr works via reference counting. Since you are destroying the only shared_ptr object (by scope), there are no references left and the memory will be freed. To get this to work you'd have to return a shared_ptr, but you said you cannot do this.