Jef*_*ffR 1 c++ code-analysis new-operator microsoft-code-analysis
这是我在进行 Visual Studio 2019 代码分析后得到的代码(警告 C26409 避免显式调用 new 和 delete,请使用 std::make_unique (r.11)。):
#include <windows.h>
#include <strsafe.h>
int main()
{
auto *sResult = new WCHAR[256];
StringCchPrintfW(sResult, 256, L"this is a %s", L"test");
delete[] sResult;
}
Run Code Online (Sandbox Code Playgroud)
我原本假设使用 new/delete 而不是 calloc/free,但现在编译器告诉我使用 std::make_unique。我找不到任何有关如何更改代码以使其兼容的示例。
所以我的问题是:
如何更改我的代码,使其不使用 new/delete
为什么我不应该使用 new/delte 与 std::make_unique ?
Mic*_*kis 10
该警告有点令人困惑,因为它假设您需要一些直接内存分配。如果事实上,你没有:
#include <windows.h>
#include <strsafe.h>
#include <vector>
int main()
{
std::vector<WCHAR> sResult(256);
StringCchPrintfW(sResult.data(), sResult.size(), L"this is a %s", L"test");
}
Run Code Online (Sandbox Code Playgroud)
或者
int main()
{
WCHAR sResult[256];
StringCchPrintfW(sResult, 256, L"this is a %s", L"test");
}
Run Code Online (Sandbox Code Playgroud)
这个想法是在可以的情况下使用静态存储(小数据)以提高效率(无操作系统内存调用),并std::vector在必须分配时使用静态存储,因为大小在编译时未知或对于堆栈来说太大并让 STL 来完成为您做的工作。的用法std::make_unique是当你确实需要直接或间接调用 new 并让它稍后自动销毁时。
TL;DR:了解现代 C++ 内存管理。