的std ::带参数复制可能不安全
问题描述:
,所以我有一块旧的代码,我试图调试的std ::带参数复制可能不安全
#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 last参数中放置一个输出迭代器。我想让这个代码符合std :: copy要我做的事情。什么是完成这个优雅的方式?
我的确在考虑制作自己的迭代器类,但真的那么优雅吗?
答
我要去,因为我想我想我已经理解了它来回答这个问题,它会帮助别人谁运行到这个问题:
事实证明,这是复制一个非常Ç方式。由于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;
}
你给了'的std :: copy'什么期望。从纯粹的C++角度来看,调用'std :: copy'没有任何问题。 – StoryTeller
我应该怎么做才能关闭警告? –
让我们退后一步。你为什么用'new'和'std :: copy'分配? – StoryTeller