Advertisement
stgatilov

Aliasing with pointers to subobjects

Jul 30th, 2015
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <memory>
  2. #include <time.h>
  3. #include <stdio.h>
  4. using namespace std;
  5.  
  6. struct IntValue {
  7.     int x;
  8.     IntValue(int x) : x(x) {}
  9. };
  10.  
  11. class MyClass_Ptr {
  12.     unique_ptr<IntValue> a, b, c;
  13. public:
  14.     MyClass_Ptr(int s)
  15.         : a(new IntValue(s))
  16.         , b(new IntValue(0))
  17.         , c(new IntValue(0))
  18.     {}
  19.     void Compute() {
  20.         a->x += b->x + c->x;
  21.         b->x += a->x + c->x;
  22.         c->x += a->x + b->x;
  23.     }
  24.     void Print() {
  25.         printf("%d\n", a->x + b->x + c->x);
  26.     }
  27. };
  28.  
  29. class MyClass_Memb {
  30.     IntValue a, b, c;
  31. public:
  32.     MyClass_Memb(int s)
  33.         : a(s)
  34.         , b(0)
  35.         , c(0)
  36.     {}
  37.     void Compute() {
  38.         a.x += b.x + c.x;
  39.         b.x += a.x + c.x;
  40.         c.x += a.x + b.x;
  41.     }
  42.     void Print() {
  43.         printf("%d\n", a.x + b.x + c.x);
  44.     }
  45. };
  46.  
  47. int main() {
  48. {
  49.     unique_ptr<MyClass_Memb> obj(new MyClass_Memb(1));
  50.     int start = clock();
  51.     for (int i = 0; i < 1000000000; i++)
  52.         obj->Compute();
  53.     obj->Print();
  54.     printf("%0.3lf\n", double(clock() - start) / CLOCKS_PER_SEC);
  55. }
  56. {
  57.     unique_ptr<MyClass_Ptr> obj(new MyClass_Ptr(1));
  58.     int start = clock();
  59.     for (int i = 0; i < 1000000000; i++)
  60.         obj->Compute();
  61.     obj->Print();
  62.     printf("%0.3lf\n", double(clock() - start) / CLOCKS_PER_SEC);
  63. }
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement