Search code examples
c++memorymemory-managementscopestdstring

C++: use std::string returned by a function: Using pointer to local variable that is out of scope


I've got the following function:

MyFunction(const char *value, bool trigger) {
    if (trigger) {
        std::string temporaryString = getTemporaryStringFromSomewhereElse();
        value = temporaryString.c_str();
    }
    // do processing here
    // I need `value` and `temporaryString.c_str();` to be alive and accessible here and not destroyed
 
    MyClass *object = new MyClass(value);
    object->Work();
    // etc..

}

So, the question is, how can I "prolong" the lifecycle of the temporaryString outside of the scope of the if-clause?

Currently, I'm getting the following error:

Using pointer to local variable 'temporary' that is out of scope.

I understand this is related to the memory management, and the fact that the temporary is assumed to be "destroyed" or cleared from the memory after the if-clause. But I need to either prolong its life cycle, or to create another string (copy) which will have a different, wider scope.

How can I achieve this?

Requirements:

  1. Function signature cannot change, it should remain: MyFunction(const char *value, bool trigger)
  2. I use the value later on to initialize another object, do some other work. I cannot have 2 variables, e.g. value and anotherValueToBeUsedIfTriggerIsTrue.

Solution

  • Simply move the declaration of the std::string out of the if block, up into the function block, eg:

    MyFunction(const char *value, bool trigger) {
        std::string temporaryString;
    
        if (trigger) {
            temporaryString = getTemporaryStringFromSomewhereElse();
            value = temporaryString.c_str();
        }
    
        // do processing here
     
        MyClass *object = new MyClass(value);
        object->Work();
        // etc..
    
    }
    

    The std::string will be blank initially, and destroyed when the function exits, and as such the reassigned value will remain valid while the function is running, as long as temporaryString is not modified.