Skip to content

Instantly share code, notes, and snippets.

@kkabdol
Created December 14, 2020 15:20
Show Gist options
  • Save kkabdol/9dbd779954705026d916e24e374667e0 to your computer and use it in GitHub Desktop.
Save kkabdol/9dbd779954705026d916e24e374667e0 to your computer and use it in GitHub Desktop.
unique_ptr example from effective modern c++
//////////////////////////////////////////
// std::unique_ptr usage
// - factory function return type for
// objects in a hierarchy.
//////////////////////////////////////////
//////////////////////////////////////////
// factory function with custom deleter
//////////////////////////////////////////
class Investment
{
public:
...
virtual ~Investment();
...
};
class Stock : public Investment { ... };
class Bond : public Investment { ... };
class RealEstate : public Investment { ... };
audo deleteInvestment = [](Investment* pInvestment)
{
makeLogEntry(pInvestment);
delete pInvestment;
};
template<typename... Ts>
auto makeInvestment(Ts&&... params) // C++14
{
std::unique_ptr<Investment, decltype(deleteInvestment)>
pInv(nullptr, deleteInvestment);
if ( /* a Stock object should be created */ )
{
pInv.reset(new Stock(std::forward<Ts>(params)...);
}
else if ( /* a Bond object should be created */ )
{
pInv.reset(new Bond(std::forward<Ts>(params)...);
}
else if ( /* a RealEstate object should be created */ )
{
pInv.reset(new RealEstate(std::forward<Ts>(params)...);
}
return pInv;
}
//////////////////////////////////////////
// usage
//////////////////////////////////////////
void usage()
{
...
// pInvestment is of type std::unique_ptr<Investment>
auto pInvestment = makeInvestment(arguments);
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment