fork(2) download
  1. //
  2. // main.cpp
  3. // TestConstness
  4. //
  5. // Created by Marco Antognini on 27/10/13.
  6. // Copyright (c) 2013 Marco Antognini. All rights reserved.
  7. //
  8.  
  9. #include <iostream>
  10. #include <memory>
  11. #include <vector>
  12.  
  13. class X {
  14. int x;
  15. public:
  16. X(int y) : x(y) { }
  17. void print() const { std::cout << "X::" << x << std::endl; }
  18. void foo() { ++x; }
  19. };
  20.  
  21. using XPtr = std::shared_ptr<X>;
  22. using ConstXPtr = std::shared_ptr<X const>;
  23.  
  24. XPtr createX(int x) { return std::make_shared<X>(x); }
  25.  
  26. void goo(XPtr p) {
  27. p->print();
  28. p->foo();
  29. p->print();
  30. }
  31.  
  32. void hoo(ConstXPtr p) {
  33. p->print();
  34. // p->foo(); // ERROR :-)
  35. }
  36.  
  37. using XsPtr = std::vector<XPtr>;
  38. using ConstXsPtr = std::vector<ConstXPtr>;
  39.  
  40. void ioo(ConstXsPtr xs) {
  41. for (auto p : xs) {
  42. p->print();
  43. // p->foo(); // ERROR :-)
  44. }
  45. }
  46.  
  47. ConstXsPtr toConst(XsPtr xs) {
  48. ConstXsPtr cxs(xs.size());
  49. std::copy(std::begin(xs), std::end(xs), std::begin(cxs));
  50. return cxs;
  51. }
  52.  
  53. void joo(XsPtr xs) {
  54. for (auto p: xs) {
  55. p->foo();
  56. }
  57. }
  58.  
  59. // ERROR :-)
  60. //XsPtr toNonConst(ConstXsPtr cxs) {
  61. // XsPtr xs(cxs.size());
  62. // std::copy(std::begin(cxs), std::end(cxs), std::begin(xs));
  63. // return xs;
  64. //}
  65.  
  66. class E {
  67. XsPtr xs;
  68. public:
  69. E() {
  70. for (auto i : { 2, 3, 5, 7, 11, 13 }) {
  71. xs.emplace_back(createX(std::move(i)));
  72. }
  73. }
  74.  
  75. void loo() {
  76. std::cout << "\n\nloo()" << std::endl;
  77. ioo(toConst(xs));
  78.  
  79. joo(xs);
  80.  
  81. ioo(toConst(xs));
  82. }
  83.  
  84. void moo() const {
  85. std::cout << "\n\nmoo()" << std::endl;
  86. ioo(toConst(xs));
  87.  
  88. joo(xs); // Should not be allowed
  89.  
  90. ioo(toConst(xs));
  91. }
  92. };
  93.  
  94. int main(int argc, const char * argv[])
  95. {
  96. std::cout << "Hello, World!\n";
  97.  
  98. XPtr p = createX(42);
  99.  
  100. goo(p);
  101. hoo(p);
  102.  
  103. E e;
  104. e.loo();
  105. e.moo();
  106.  
  107. // WORKS!
  108.  
  109. return 0;
  110. }
  111.  
  112.  
Success #stdin #stdout 0s 3484KB
stdin
Standard input is empty
stdout
Hello, World!
X::42
X::43
X::43


loo()
X::2
X::3
X::5
X::7
X::11
X::13
X::3
X::4
X::6
X::8
X::12
X::14


moo()
X::3
X::4
X::6
X::8
X::12
X::14
X::4
X::5
X::7
X::9
X::13
X::15