开发者

stoi - issue with design

I've asked in one of my posts a question about alternative to boost::lexical_cast and amongst many replies I've got one suggestion stoi as a viable alternative.

I've decided to test it and to my surprise as a second argument to this function (argument describing size) is a pointer to size_t type, not actual size_t type. Is there any logical explanation for that and in what way it is better to have 开发者_如何转开发a pointer to actual object than object itself (just in this particular case when size is concerned and I wouldn't instinctively assign size with pointer)?

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


That is a way of having optional arguments. Basically, if you are interested in knowing which is the first character that was not converted into the number. If you are not really interested in that result, you can pass nullptr.

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

This is meant to be used 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;
}

By using a pointer you can make the argument really optional, if it was an out parameter, but required a reference would be used, but that would require user code to create the variable always regardless of whether they are interested in the value or not, so it would not be really optional.


I thought the size_t* parameter was a pointer to a variable into which stoi places a position within the string after the end of the converted number. i.e. it's an 'out' parameter, hence being a pointer.

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

Perhaps you should point to the specific docs which are confusing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜