【问题标题】:std::copy with parameters that may be unsafe带有可能不安全的参数的 std::copy
【发布时间】:2017-11-03 23:12:49
【问题描述】:

所以我有一段旧代码正在尝试调试

#include <string>
#include <map>

int main()
{
  std::map<std::wstring, std::wstring> filters;

  ...
  for (auto filterIter : filters)
{
   ...
   wchar_t* nameArray = new wchar_t[filterIter.first.size() + 1];
   std::copy(filterIter.first.begin(), filterIter.first.end(), nameArray);
   nameArray[filterIter.first.size()] = '\0';
   ...
   LPCWSTR pszName = nameArray;
}

getchar();
return 0;
}

这里的问题是我收到这个警告说:

warning C4996: 'std::copy::_Unchecked_iterators::_Deprecate': Call to 'std::copy' 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'

我想解决此警告,而不必使警告静音。我知道问题在于 nameArray 是常规指针而不是 Output iterator 。 std::copy 想让我在 std::copy 最后一个参数中放入一个输出迭代器。我想让这段代码符合 std::copy 想要我做的事情。有什么优雅的方式来实现它?

我确实考虑过创建自己的迭代器类,但这真的那么优雅吗?

【问题讨论】:

  • 你给了std::copy它的期望。从纯 C++ 的角度来看,调用 std::copy 没有任何问题。
  • 我应该怎么做才能关闭警告?
  • 让我们退后一步。你为什么用new分配,用std::copy
  • 我猜是因为nameArray 后来被分配给这个名为pszName 的变量,其中pszName 被#defined 为 wchar_t
  • 你应该怎么做才能关闭警告?阅读整个警告怎么样(它字面意思是如何)!

标签: c++ visual-c++ copy c++14


【解决方案1】:

我将回答这个问题,因为我认为我已经弄明白了,它会帮助遇到这个问题的其他人:

事实证明,这是一种非常 C 的复制方式。由于LPCWSTR 只是底层的 wchar_t,所以我最终只是这样做,并且不再出现编译器错误。我将运行测试以确保此函数的行为仍然相同。

注意:我没有编写此代码,这只是我正在查看的遗留代码。

这是更新的版本

#include <string>
#include <map>

int main()
{
  std::map<std::wstring, std::wstring> filters;

  ...
  for (auto filterIter : filters)
{
  ...
  LPCWSTR pszName = filterIter.first.c_str();
  ...
}

getchar();
return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 2021-06-02
    • 2013-10-05
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多