Conversion from 'xxxx' to 'yyyy', possible loss of data, suppression?

谁说胖子不能爱 提交于 2019-12-24 07:27:54

问题


Sometimes I've got warnings with conversion from a longer type to a smaller type e.g.:

void f( unsigned short i ) // f - accept any numeric type
                           // smaller than std::vector<>::size_type
{}

std::vector < some_type > v;
..
f ( v.size() );

Usually I was using one of next solutions:

assert( v.size() <= std::numeric_limits< unsigned short >::max() );
f( static_cast< unsigned short >( v.size() ) );

or

f( boost::numeric_cast<  unsigned short >( v.size() ) );

But on my present work boost not used and from last month asserts are disallowed.

What other safe ways you know for suppress this warning?
Any pitfalls in discribed ways?

PS: It is not always possible to change the signature of f, also sometimes really should accept small numeric type.

EDITED: I want to make conversion as safe as possible.


回答1:


Why cast in the first place? The vector's size is typically an unsigned integer. If possible, I'd say update the function signature. Warnings are not meant to be suppressed, rather addressed.




回答2:


The only safe way to deal with this is to ensure that you do not have a loss of conversion at runtime. The assert code will only work during debug builds and will allow for a conversion loss in retail builds. The conversion loss is bad because it will pass around a completely incorrect size for the vector.

What you really need is a mechanism to prevent you from creating data loss. I reccomend using a class like SafeInt. This will prevent a conversion which overflows or underflows by means of throwing an exception.

SafeInt<size_t> size = v.size();
f((unsigned short)size);  // Throws if size can't fit in an unsigned short

SafeInt: http://www.codeplex.com/SafeInt




回答3:


I will now repeat my mantra again: If your code contains casts, there is probably something wrong with the code or the design and you should examine both with a view to removing the cast.

BTW, you upvoted this the last time I posted it!




回答4:


As size() usually returns an unsigned integer, it should be quite safe to typecast it to a signed one.

f(static_cast<expected-type>(v.size()));

Otherwise change the function signature, if it is possible.



来源:https://stackoverflow.com/questions/717022/conversion-from-xxxx-to-yyyy-possible-loss-of-data-suppression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!