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 converting 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?
On a typical 64-bit system, the size_t will be 64-bit, but unsigned int will be 32 bit. So we cannot use them interchangeably. One standard recommendation is that the size_t be at most as big as an unsigned long.
gcc actually defines size_t as a signed integer type. This means that using size_t rather than an explicit integer type actually *creates* portability annoyance when code is used both with gcc and with a compiler that defines size_t as an unsigned integer type.
size_t is the unsigned integer type of the result of sizeof , _Alignof (since C11) and offsetof, depending on the data model. The bit width of size_t is not less than 16.
Yes, size_t is guaranteed to be an unsigned type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With