code_junkie

Constants and compiler optimization in C++

Nov 11th, 2011
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. void someType::somefunc();
  2.  
  3. void MyFunc()
  4. {
  5. someType A(4); //
  6. Fling(A.m_val);
  7. A.someFunc();
  8. Flong(A.m_val);
  9. }
  10.  
  11. class Test
  12. {
  13. public:
  14. Test (int value) : m_value (value)
  15. {
  16. }
  17.  
  18. void SetValue (int value) const
  19. {
  20. const_cast <Test&>(*this).MySetValue (value);
  21. }
  22.  
  23. int Value () const
  24. {
  25. return m_value;
  26. }
  27.  
  28. private:
  29. void MySetValue (int value)
  30. {
  31. m_value = value;
  32. }
  33.  
  34. int
  35. m_value;
  36. };
  37.  
  38. void modify (const Test &test, int value)
  39. {
  40. test.SetValue (value);
  41. }
  42.  
  43. void main ()
  44. {
  45. const Test
  46. test (100);
  47.  
  48. cout << test.Value () << endl;
  49. modify (test, 50);
  50. cout << test.Value () << endl;
  51. }
  52.  
  53. 100
  54. 50
  55.  
  56. volatile const
  57.  
  58. #include <iostream>
  59. using namespace std;
  60.  
  61. void swap (const int &a, const int &b)
  62. {
  63. int
  64. c = a;
  65. const_cast <int&>(a) = b;
  66. const_cast <int&>(b) = c;
  67. }
  68.  
  69. void main ()
  70. {
  71. const int a = 10;
  72. const int b = 20;
  73. int c = 30;
  74. swap (a,b);
  75. cout << "a = " << a << endl;
  76. cout << "b = " << b << endl;
  77. swap (c,b);
  78. cout << "b = " << b << endl;
  79. cout << "c = " << c << endl;
  80. }
  81.  
  82. a = 10;
  83. b = 20;
  84.  
  85. b = 20;
  86.  
  87. c = 10;
  88.  
  89. void f(Type dont_modify); // or
  90. void f(Type const& dont_modify);
Add Comment
Please, Sign In to add comment