Size_t for unsigned int (from API function)

I use the Oracle API to access the database, and this API has a readBuffer(char * buffer, unsigned int size); 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 std::string and unsigned int for size, the problem is that when I pass std::string.size() the size argument of my function, I I get a warning from my compiler that converting from size_t to unsigned int could result in data loss.

I wondered if there is a valid way to convert size_t to unsigned int , so I can pass it to my API and not get a warning from the compiler?

I understand that the purpose of size_t and google search for this conversion leads to a large number of results that say "change the function to accept the argument size_t", but I CANNOT change the signature of my API in this case.

Any suggestions?

+6
source share
5 answers

Yes, write a helper function that will check if such a conversion is valid and throw an exception differently. Sort of:

 unsigned int convert( size_t what ) { if( what > UINT_MAX ) { throw SomeReasonableException(); } return static_cast<unsigned int>( what ); } 
+15
source

Ok, do static_cast<unsigned int>(mystring.size()) .

The reason is that std::size_t usually has a pointer size, but there are 64-bit platforms on which int is still 32 bits. In this case, the only reason for data loss will be that the specified string has a length of more than 2 ^ 32 bytes.

If you know that this will not happen, put assert somewhere to catch this case, and the static_cast compiler will shut down.

+5
source
 static_cast<unsigned int>(str.size()); 

If you want to be paranoid:

 if (static_cast<unsigned int>(str.size()) != str.size()) throw ... 
+4
source

You can force convert with

 static_cast<unsigned int>(your_variable) 

to build. Of course, the correct way would be for the API to accept size_t ...

+1
source

The risk here is that size_t may be larger ( unsigned ) int , and thus you cannot safely convert if that is the case.

For example, it is possible that int is 32 bits and size_t is 64 bits. I do not know such a system / configuration from the top of my head, but it can happen.

For most β€œsmart” systems, both will have at least 32 bits, and a single 4 GB line is still (possibly) unlikely to happen.

So, you can just quit, that would be valid, but it would not be β€œsafe” for all possible systems and angular cases.

+1
source

Source: https://habr.com/ru/post/886226/


All Articles