Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, strings, and pointers

I know this is rudimentary but I know nothing about C++. Is it necessary to do:

string *str = getNextRequest();

rather than

string str = getNextRequest();

in order to reference str later on in the same block of code? If so, what type of error would the latter produce?


1 Answers

That depends entirely on the return type of getNextRequest.

Strings can be used and reused throughout the scope they're declared in. They essentially contain a mutable C string and some handling information, helper methods, etc.

You can, very safely, return a string from a function and the compiler will make a copy or move it as necessary. That string (str here) can then be used normally, with no worries about using out-of-scope locals or such.

There are times when a pointer to a string is needed, but unless you're using it as an out parameter, those tend to be rare and indicate some design oddity.

like image 183
ssube Avatar answered Apr 02 '26 02:04

ssube