代码之家  ›  专栏  ›  技术社区  ›  Amit G.

STL API的差异(当我将平台从x64切换到x86时,VS2017)

  •  -1
  • Amit G.  · 技术社区  · 8 年前

    我有这个简单的readtextfile(完整路径)函数:

    std::wstring CEngine::load_text_file(std::wstring &full_path)
    {
        std::wstring buffer = m_text_file_cache[full_path];
    
        if (buffer.empty()) // Load file:
        {
            std::wifstream wif(full_path);
    
            wif.seekg(0, std::ios::end);
            buffer.resize(wif.tellg()); // On Debug/Release x86: Warning C4244: 'argument': conversion from 'std::streamoff' to 'const unsigned int', possible loss of data
            wif.seekg(0);
            wif.read(buffer.data() , buffer.size()); // On Debug/Release x86: Error C2664: 'std::basic_istream<wchar_t,std::char_traits<wchar_t>> &std::basic_istream<wchar_t,std::char_traits<wchar_t>>::read(_Elem *,std::streamsize)': cannot convert argument 1 from 'const wchar_t *' to 'wchar_t *'
    
            m_text_file_cache[full_path] = buffer;
        }
    
        return buffer;
    }
    
    • m_text_file_cache 只是一个STD::MAP缓存以减少磁盘I/O忽略它。

    当我编译到x64(主轨)时没有问题,但当我编译到x86(出于好奇)时,有两个问题在代码中用注释标记:警告C4244&error C2664。

    2 回复  |  直到 8 年前
        1
  •  3
  •   Xirema    8 年前

    导致此警告的原因是,即使您处于x86模式,文件仍被假定(可能)大于4GB,这意味着它们的大小类型为64位。64位整数截断为32位整数,并显示一个警告,这是编译器提供的警告。 static_cast unsigned int 修复。

    由于x86配置可能不在C++ 17模式下编译,因此导致错误。 data() 函数返回 wchar_t const* 而不是C++ 17的返回行为 wchar_t * . 更改编译器标志以编译C++ 17模式,不再需要强制转换了。最好是为“所有”配置设置标志,这样以后就不必手动更改这两个配置。

    另外,不要使用C样式的强制转换来解决这个问题,比如 (wchar_t*)buffer.data() const_cast

    wif.read(const_cast<wchar*>(buffer.data()) , buffer.size());
    
        2
  •  0
  •   Amit G.    8 年前

    size_t MSDN MSDN tellg() std::streamoff long long

    std::wstring :: resize (size_type n);
    

    discussed here