Stoi - design problem

I asked in one of my posts a question about the alternative to boost::lexical_cast and among many answers I have one stoi suggestion as a viable alternative.
I decided to test it and, to my surprise, as a second argument to this function (an argument describing the size), is a pointer to the size_t type, and not the actual size_t type. Is there a logical explanation for this and how is it better to have a pointer to the actual object than the object itself (just in this particular case, when the size is touching, and I would not instinctively assign the size using the pointer)?

Link to stoi doc: http://msdn.microsoft.com/en-us/library/ee404860.aspx

+1
c ++
Jun 20 '11 at 7:01
source share
2 answers

This is a way to have optional arguments. Basically, if you are interested in knowing who is the first character that has not been converted to a number. If you are not very interested in this result, you can pass nullptr.

§21.5 [string.conversions] / 1 [...] If the function does not throw an exception and idx! = 0, the function saves in * idx the index of the first uncured str element.

It is intended for use as:

 int main() { std::string two{"2 and more contents"}; // I don't care, just want a number: int i = std::stoi( two, 0, 10 ); // base = 0 std::size_t first_not_converted; int i = std::stoi( two, &first_not_converted, 10 ); std::cout << "Unconverted string is: " << two.substr( first_not_converted ) << std::endl; } 

Using a pointer, you can make the argument really optional if it was an out parameter, but required the link to be used, but this will require user code to create the variable always regardless of whether it is interested in the value or not, so it will not be really optional .

+4
Jun 20 2018-11-11T00:
source share

I thought the size_t * parameter was a pointer to a variable in which stoi puts the position in the string after the end of the converted number. that is, the out parameter is therefore a pointer.

For example: http://msdn.microsoft.com/en-us/library/ee404860.aspx

Perhaps you should point out certain documents that are confusing.

+2
Jun 20 2018-11-11T00:
source share



All Articles