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:
- Function signature cannot change, it should remain:
MyFunction(const char *value, bool trigger) - I use the
valuelater on to initialize another object, do some other work. I cannot have 2 variables, e.g.valueandanotherValueToBeUsedIfTriggerIsTrue.
temporaryStringand assign to thevauledirectly?std::optional. This is the most readable kind of code for my point of view