Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ compiler waring C26409 – avoid calling new and delete

Here is my code that I’m getting (Warning C26409 Avoid calling new and delete explicitly, use std::make_unique instead (r.11).) after doing a Visual Studio 2019 Code Analysis:

#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;
}

I was under the assumption to use new/delete instead of calloc/free, but now the compiler is telling me to use std::make_unique. I can’t find any examples on how I can change my code to be compliant.

So my questions are:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. how do I change my code so it doens’t use new/delete

  2. why should I not use new/delte vs std::make_unique?

>Solution :

The warning is somewhat confusing, because it assumes that you do need some direct memory allocation. If fact, you don’t:

#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");
}

or

int main()
{
    WCHAR sResult[256];
    StringCchPrintfW(sResult, 256, L"this is a %s", L"test");
}

The idea is to use static storage when you can (small data) to be more efficient (no OS memory call), and use std::vector when you must allocate because the size is either unknown at compile time or too big for the stack. The usage of std::make_unique is when you indeed need to call new directly or indirectly and have it auto-destruct later.

TL;DR: Read about modern C++ memory management.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading