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

后端 未结 2 1387
野的像风
野的像风 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 21:49

    Use the correct type (option 2) - the function/interface defines that type for you, use it.

    std::size_t size = v.size(); // given vector<>::size_type is size_t
    // or a more verbose
    decltype(v)::size_type size = v.size();
    

    It goes to the intent... you are getting the size of v and that size has a type. If the correct type had been used from the beginning, this would not have been a problem.

    If you require that value later as another type, transform it then; the safe_cast<> is then a good alternative that includes the runtime bounds checking.

    Option 6. Use auto

    When you use size = v.size(), if you are not concerned what the type is, only that you use the correct type,

    auto size = v.size();
    

    And let the compiler do the hard work for you.

提交回复
热议问题