size_t到unsigned int(来自API函数)

Ton*_*ion 8 c++ size-t

我使用Oracle API访问数据库,此API具有readBuffer(char * buffer, unsigned int size);我无法进行任何更改的功能.

我有一个使用这个API的类,我的函数的签名当前需要a std::string和一个unsigned int大小,问题是,当我传递std::string.size()给我的函数的size参数时,我收到编译器的警告,转换size_tunsigned intcan导致数据丢失.

我想知道是否有一种有效的方法将其转换size_t为一个unsigned int所以我可以将它传递给我的API而不是从编译器得到警告?

我理解为size_t的目的和谷歌搜索此转换变成了很多结果说:"改变采取的size_t ARG功能",但我CAN NOT改变我的API的签名在这种情况下.

有什么建议?

sha*_*oth 18

是的,编写一个辅助函数来检查这种转换是否有效,否则抛出异常.就像是:

unsigned int convert( size_t what )
{
    if( what > UINT_MAX ) {
       throw SomeReasonableException();
    }
    return static_cast<unsigned int>( what );
}
Run Code Online (Sandbox Code Playgroud)

  • `boost :: numeric_cast`或多或少地做到这一点. (4认同)

Ale*_*ler 5

好吧,做一个static_cast<unsigned int>(mystring.size()).

原因std::size_t通常是指针大小,但有64位平台int仍然是32位.在这种情况下,数据丢失的唯一原因是所讨论的字符串长度超过2 ^ 32字节.

如果你知道不会发生assert这种情况,可以static_cast在某个地方找到这种情况并让编译器保持沉默.