Last active
September 20, 2016 13:27
-
-
Save fenbf/b4090f5d4eabbcbfa4a7fd6069643af5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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