How to use unique_ptr with the new operator

I highlight a piece with a scratch in memory with input size, and I would like to use it unique_ptrto track the correct life span without any apparent concern about freeing it. Here is what I came up with:

{
    std::unique_ptr<BYTE> sp;
    sp.reset(reinterpret_cast<BYTE*>(operator new (100)));
}

I had to use BYTEsince MSVC will not compile with std::unique_ptr<void>. Operators of my testing newand deletecalled expected. Since this is a slightly unusual use (i.e., Use operator newexplicitly), I wanted to check if there was anything wrong with that? And are there any alternatives that could be better / cleaner?

+4
source share
1

, new[], unique_ptr . a unique_ptr delete delete[], , undefined. :

std::unique_ptr<BYTE[]> sp(new BYTE[100]);

VS2013, new make_unique.

auto sp = make_unique<BYTE[]>(100);

, make_unique , .


operator new, , operator delete, .

std::unique_ptr<BYTE, void(*)(BYTE *)> sp(static_cast<BYTE *>(::operator new(100)),
                                          [](BYTE *p) { ::operator delete(p);} );
+7

Source: https://habr.com/ru/post/1545925/


All Articles