fork(2) download
  1. #include <alloca.h>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. struct Base
  6. {
  7. virtual ~Base() { }
  8. virtual int to_int() const = 0;
  9. };
  10.  
  11. struct Integer : Base
  12. {
  13. Integer(int n) : n_(n) { }
  14. int to_int() const { return n_; }
  15. int n_;
  16. };
  17.  
  18. struct Double : Base
  19. {
  20. Double(double n) : n_(n) { }
  21. int to_int() const { return -n_; }
  22. double n_;
  23. };
  24.  
  25. inline Base* factory(double d) __attribute__((always_inline));
  26.  
  27. inline Base* factory(double d)
  28. {
  29. if ((double)(int)d != d)
  30. return new (alloca(sizeof(Double))) Double(d);
  31. else
  32. return new (alloca(sizeof(Integer))) Integer(d);
  33. }
  34.  
  35. int main()
  36. {
  37. std::vector<Base*> numbers;
  38. numbers.push_back(factory(29.3));
  39. numbers.push_back(factory(29));
  40. numbers.push_back(factory(7.1));
  41. numbers.push_back(factory(2));
  42. numbers.push_back(factory(231.0));
  43. std::cerr << "iterating...\n";
  44. for (std::vector<Base*>::const_iterator i = numbers.begin();
  45. i != numbers.end(); ++i)
  46. {
  47. std::cout << *i << ' ' << (*i)->to_int() << '\n';
  48. (*i)->~Base(); // optionally / Undefined Behaviour iff the
  49. // program depends on side effects of destructor
  50. }
  51. }
  52.  
Success #stdin #stdout #stderr 0s 3432KB
stdin
Standard input is empty
stdout
0xbfbd5d90 -29
0xbfbd5d70 29
0xbfbd5d50 -7
0xbfbd5d30 2
0xbfbd5d10 231
stderr
iterating...