I have some basic questions about C ++, consider the following code in which I try to return the string .
const std :: string & amp; NumberHolder :: getValueString () {char valueCharArray [100]; Sprintf_s (valueCharArray, "% f", _ value); Std :: string valueString (valueCharArray); Return value string; } I am trying to return a string called the value of client member with _value. Although I am getting warnings that I am trying to return a pointer to the local variable. This is definitely a bad thing if I consider C ++ enough at this point, it means that the pointer I pass will be removed before that time when someone tries to use it Therefore I am modified:
const std :: string & amp; NumberHolder :: getValueString () {char valueCharArray [100]; Sprintf_s (valueCharArray, "% f", _ value); Std :: string valueString = new std :: string (valueCharArray); Return (* value string); } On this stack, a pointer should be created which will be left outside of this function. Here are two problems: 1) It is not compiled in any way and I do not understand why (error = 'std :: string *' from 'std :: basic_string & lt; _Elem, _Traits , _Ax> '' ) and 2) It looks like a possible memory leak because I depend on someone else to call to remove this person. Which method should I use here?
You assign a std :: string to it on a heap!
Just return it from the value like this:
std :: string NumberHolder :: getValueString () {Value description from around [100]; Sprintf_s (valueCharArray, "% f", _ value); Return std :: string (valueCharArray); } Now what will happen on the return details of every compiler, so no copies should be made. Consider the following:
Number Holder Holder; // ... std :: string returnString = holder.getValueString (); With RVO, the compiler will generate code for the above implementation of code: NumberHolder :: getValueString () such as std :: string Created in place of returnedString , therefore no copy is required.
Comments
Post a Comment