Home > Mobile >  C pointer to std::string updated in function - scope issue? (ESP32)
C pointer to std::string updated in function - scope issue? (ESP32)

Time:02-06

I have a

std::string 

and pass that by reference to a function.

The function dereferences the parameter (pointer) into a local std::string for ease of working.

I update the local string's value and then update the pointer.

Have I just pointed to something that's gone out of scope? Or have I updated the underlying value of the string pointed to by string abc in the example below?

BTW It works but I'm concerned I'm breaking C rules.

int main() {
  
  std::string abc = R"(This is a string "raw" literal)";
  
  updateStringValue(&abc);

  log_v(abc.c_str());

}

void updateStringValue(std::string *theData) {

  std::string localString = (*theData);

  localString.append("some other value");

  *theData = localString;
}

I realise that the local string "localString" only survives the function but has the amended value really been retained (or maybe it's still floating around in memory but now out of scope once the function ends)?

I expected this to work (it did) but am having doubts.

Previously I did not dereference the incoming data's pointer into a local string but the resulting syntax was more confusing (to others) so I did it this way to simplify the overall structure.

I've definitely confused myself now.

CodePudding user response:

It works fine. *theData = localString; invokes copy assignment, so the caller's string is changed to be equivalent to (but not the same object as) localData. After that, localData gets cleaned when the function returns, but that's fine, the copy has already occurred.

To be clear, you did not pass by reference (that would be void updateStringValue(std::string& theData), with an &, not a *, and no need for the caller to explicitly take the address of their local variable). Passing-by-reference would save you the need to manually dereference the pointer.

Also note, there's no need to make the copy here. You could just call:

theData->append("some other value");

or if you used a true reference:

theData.append("some other value");

and save the local copy and copy-back entirely.

  • Related