fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. int treasury = 1000000;
  5.  
  6. class Investment {
  7. int value_;
  8. public:
  9. static const int MINIMUM = 25;
  10.  
  11. Investment() : value_(0) {}
  12. virtual ~Investment() { }
  13. void buy(int amount) { value_ += amount; }
  14.  
  15. static void seize(Investment *inv){
  16. if(inv)
  17. treasury += inv->value_;
  18. delete inv;
  19. }
  20. };
  21.  
  22. class Bond : public Investment {
  23. };
  24.  
  25. class Stock : public Investment {
  26. };
  27.  
  28. std::shared_ptr<Investment> createInvestment(bool buy_stock) {
  29. // Why bother with the deleter here:
  30. //std::shared_ptr<Investment> inv(nullptr, Investment::seize);
  31.  
  32. // this works just as well:
  33. std::shared_ptr<Investment> inv;
  34.  
  35. if (buy_stock) {
  36. //inv = std::shared_ptr<Investment>(new Stock(), Investment::seize);
  37. inv.reset(new Stock(), Investment::seize);
  38. //inv.reset(new Stock()); // This seems to remove the existing deleter
  39. } else {
  40. inv.reset(new Bond(), Investment::seize);
  41. }
  42.  
  43. inv->buy(Investment::MINIMUM);
  44.  
  45. return inv;
  46. }
  47.  
  48. void playTheMarkets() {
  49. std::shared_ptr<Investment> stocks(createInvestment(true));
  50. std::shared_ptr<Investment> bonds(createInvestment(false));
  51. }
  52.  
  53. int main() {
  54. playTheMarkets();
  55. std::cout << treasury << std::endl;
  56. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
1000050