【发布时间】: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