我只是在代码中使用这些宽字 rune 字来了解它们
wchar_t* wpsub = wcstok(names, names_delim);
wpsub = wcstok(NULL, names_delim);
wchar_t* wcopied=new wchar_t[wcslen(wname) + 1];
strcpy(nameptr, "singh");
wcscpy(wcopied, wname);
wcscat(wcopied, L" Singh");
为什么我会收到这些警告,我还是忽略了它。 我们是否需要忽略任何此类警告。
: warning C4996: 'wcstok': This function or variable may be unsafe. Consider using wcstok_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
: see declaration of 'wcstok'
: warning C4996: 'wcstok': This function or variable may be unsafe. Consider using wcstok_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
: see declaration of 'wcstok'
: warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
: see declaration of 'strcpy'
: warning C4996: 'wcscpy': This function or variable may be unsafe. Consider using wcscpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
: see declaration of 'wcscpy'
: warning C4996: 'wcscat': This function or variable may be unsafe. Consider using wcscat_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
: see declaration of 'wcscat'
最佳答案
不使用原来的strtok family function还有另一个原因:
[...] However, within a single thread, interleaving calls to one of these functions is highly likely to produce data corruption and inaccurate results. When parsing different strings, finish parsing one string before starting to parse the next. Also, be aware of the potential for danger when calling one of these functions from within a loop where another function is called. If the other function ends up using one of these functions, an interleaved sequence of calls will result, triggering data corruption.
原因是 strtok
不可重入:设计时,人们认为使用全局变量作为上下文的存储库是一个好主意(您认为 >strtok
能记住每个函数调用之间从哪里继续吗?)。
过去的已经过去了,我们不应该评判几十年前的代码,但是,随着所有新标准(我想到了 C99),我仍然对这个函数没有被重构感到惊讶。
至少,strtok_s family of function Microsoft 制作的程序使用用户提供的变量(称为context
)。如果您可以选择,对于生产代码,请使用 strtok_s
。
如果您需要提供跨平台代码,我的建议是:
- 编写一个函数,该函数将用作真实函数的间接调用
- 在 Windows 上,重定向到 strtok_s
- 在任何有安全 strtok 的平台上(我在谷歌搜索时找到了
strtok_r
),重定向到该函数 - 在没有安全strtok的平台上,编写自己的strtok(这并不困难,并且是学习编程的一个很好的练习)
现在,这些 C 函数有 C++ 替代品,可以组合 std::string
methods一起,或使用boost::tokenizer
关于c++ - 类似 'wcstok' : This function or variable may be unsafe. 的警告请考虑使用 wcstok_s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6007594/