Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// compile at https://godbolt.org/g/yb47Aq
//
#include <iostream>
#include <memory>
class Widget
{
public:
void DoStuff() { }
};
void PrintError() { }
bool LegacySink(Widget *pWidget, int a) // owns widget on success
{
if (a == 0)
return false;
delete pWidget;
return true;
}
void TestOld()
{
Widget * pW1 = new Widget();
Widget * pW2 = new Widget();
Widget * pW3 = new Widget();
if (!LegacySink(pW1, 1))
{
delete pW1;
delete pW2;
delete pW3;
PrintError();
return;
}
if (!LegacySink(pW2, 1))
{
// delete pW1; // not needed, already in sink!
delete pW2;
delete pW3;
PrintError();
return;
}
if (!LegacySink(pW3, 1))
{
// delete pW1; // not needed, already in sink!
// delete pW2; // not needed, already in sink
delete pW3;
PrintError();
return;
}
}
void TestOldImproved()
{
// one
Widget * pW1 = new Widget();
if (!LegacySink(pW1, 1))
{
delete pW1;
PrintError();
return;
}
// two
Widget * pW2 = new Widget();
if (!LegacySink(pW2, 1))
{
delete pW2;
PrintError();
return;
}
// three
Widget * pW3 = new Widget();
if (!LegacySink(pW3, 1))
{
delete pW3;
PrintError();
return;
}
}
void TestNew()
{
// one
auto pW1 = std::make_unique<Widget>();
if (!LegacySink(pW1.get(), 1))
{
PrintError();
return;
}
// two
auto pW2 = std::make_unique<Widget>();
if (!LegacySink(pW2.get(), 1))
{
PrintError();
return;
}
// three
auto pW3 = std::make_unique<Widget>();
if (!LegacySink(pW3.get(), 1))
{
PrintError();
return;
}
}
int main()
{
TestOld();
TestOldImproved();
TestNew();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.