2

免责声明:这只是初学者的另一项任务,所以我很高兴在不同的编译器和不同的架构上我可能会得到不同的(不兼容的)二进制文件。所以没关系,它只适用于这台特定的机器。

我正在写入和读取size_t二进制文件。写作看起来像:

std::string result;
result.append((char *)&block_size_, sizeof(block_size_));

不久之后将result其写入文件。

但是当我以同样的方式阅读它时:

map_binary.copy((char *)&block_size_, sizeof(block_size_), offset);

我收到警告

warning C4996: 'std::basic_string<_Elem,_Traits,_Alloc>::copy': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring(1777) : see declaration of 'std::basic_string<_Elem,_Traits,_Alloc>::copy'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]

我不明白为什么这段代码不安全并寻找解决方案,而不是假装根本没有问题(使用-D_SCL_SECURE_NO_WARNINGS)。

那么,我错过了什么?

PS:现在我只使用标准库学习 C++,所以使用boost或其他东西的解决方案是不可接受的。

4

1 回答 1

1

你没有错过任何东西。如果您将任何内容复制到指针,VC++ 会非常热衷于警告您。在这种情况下,无法保证您将获得正确的目的地大小。毕竟,您可能会编写类似这样的内容map_binary.copy((char *)&block_size_, 4, offset);,然后发现您的代码在 64 位编译器中失败。

如果您对避免此类错误的能力感到满意,请禁用或忽略该警告。

于 2012-10-18T09:21:35.660 回答