What's the best strategy to get rid of “warning C4267 possible loss of data”?

后端 未结 2 1389
野的像风
野的像风 2021-02-14 21:29

I ported some legacy code from win32 to win64. Not because the win32 object size was too small for our needs, but just because win64 is more standard now and we wish to port all

2条回答
  •  别那么骄傲
    2021-02-14 22:00

    IFF you have time pressure to get the code warning free, I would initially disable the warning -- your code used to work with this, and it is, IMHO, extremely unlikely that in cases where you assign to a 32bit size you'll exceed it. (4G values in a collection - I doubt that'll fly in normal applications.)

    That being said, for cases other than collections, the warning certainly has merit, so try to get it enabled sooner or later.

    Second when enabling it and fixing the code, my precedence would be:

    • Use auto (or size_t pre C++11) for locals where the value is not further narrowed.
    • For when narrowing is necessary, use your safe_cast if you can justify the overhead of introducing it to your team. (learning, enforcing, etc.)
    • Otherwise just use static_cast:

      I do not think this is a problem with collections. If you do not know better to the contrary, your collection will never have more than 4G items. IMHO, it just doesn't make sense to have that much data in a collection for any normal real world use cases. (that's not to say that there may not be the oddball case where you'll need such large data sets, it's just that you'll know when this is the case.)

      For cases where you actually do not narrow a count of a collection, but some other numeric, the narrowing is probably problematic anyway, so there you'll fix the code appropriately.

提交回复
热议问题