代码之家  ›  专栏  ›  技术社区  ›  bayda

从'xxxx'转换为'yyyy',可能丢失数据,抑制?

  •  1
  • bayda  · 技术社区  · 16 年前

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

    通常我会使用下一种解决方案:

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

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

    您知道哪些其他安全方法来抑制此警告?
    在描述的方式中有什么陷阱吗?

    附言: 不可能总是更改f的签名,有时也确实应该接受小数字类型。

    编辑时间: 我想使转换尽可能安全。

    4 回复  |  直到 16 年前
        1
  •  7
  •   dirkgently    16 年前

    为什么一开始就投?向量的大小通常是无符号整数。如果可能的话,我会说更新函数签名。 警告不是要被压制,而是要被解决。

        2
  •  3
  •   JaredPar    16 年前

    处理这个问题的唯一安全方法是确保在运行时不会丢失转换。断言代码仅在调试生成期间工作,并允许零售生成中的转换丢失。转换损失很糟糕,因为它会传递一个完全不正确的向量大小。

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

    保险箱: http://www.codeplex.com/SafeInt

        3
  •  2
  •   anon anon    16 年前

    我现在重复我的咒语 :如果您的代码包含强制转换,则代码或设计可能有问题,您应该同时检查这两个问题,以便删除强制转换。

    顺便说一句,我上一次发这个的时候你投了高票!

        4
  •  2
  •   Jens Luedicke    16 年前

    由于size()通常返回一个无符号整数,将其类型转换为有符号整数应该是非常安全的。

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

    否则,如果可能,请更改函数签名。