I am using the Oracle API to access a database and this API has a function readBuffer(char * buffer, unsigned int size);
to which I cannot make any changes.
I have a class that uses this API and the signature of my function currently takes a std::string
and an unsigned int
for the size, the problem is that when I pass std::string.size()
to the size argument of my function, I get a warning from my compiler that convertin开发者_Python百科g from size_t
to unsigned int
could cause data loss.
I wondered if there is a valid way to convert the size_t
to an unsigned int
so I can pass it to my API and not get a warning from the compiler?
I understand the purpose of size_t and searching google for this conversion turns up a lot of results that say "change the function to take a size_t arg" but I CANNOT change the signature of my API in this case.
Any suggestions?
Yes, write a helper function that will check whether such conversion is valid and throw an exception otherwise. Something like:
unsigned int convert( size_t what )
{
if( what > UINT_MAX ) {
throw SomeReasonableException();
}
return static_cast<unsigned int>( what );
}
Well, do a static_cast<unsigned int>(mystring.size())
.
The reason is that std::size_t
is usually pointer-size, but there are 64 bit platforms on which an int
is still 32 bits. In this case, the only reason for data loss would be if the string in question had a length of more than 2^32 bytes.
If you know that this won't happen, put an assert
somewhere to catch this case and static_cast
the compiler to silence.
static_cast<unsigned int>(str.size());
If you want to be paranoid:
if (static_cast<unsigned int>(str.size()) != str.size())
throw ...
You can force the conversion using the
static_cast<unsigned int>(your_variable)
construct. Of course the correct way would be for the API to accept size_t
...
The risk here is that size_t
might be larger than (unsigned
) int
, and thus you cannot safely convert if that is the case.
For instance, it's conceivable that int
is 32 bits, while size_t
is 64 bits. I don't know such a system/configuration off the top of my head, but it could occur.
For most "reasonable" systems, both will be at least 32 bits, and a single 4 GB string is still (perhaps) unlikely to occur.
So then you could just cast, that would be valid but it would not be "safe" for all possible systems and corner cases.
精彩评论