#include using std::vec" /> #include using std::vec" /> #include using std::vec"/>

How can the execute-around-pointer code invoke an operator->() twice, although I only dereference once?

64 Views Asked by At

Consider the following code, lifted from this page regarding the "execute around pointer" idiom":

#include <vector>
#include <iostream>

using std::vector;

class VisualizableVector {
  public:
    class proxy {
      public:
        proxy (vector<int> *v) : vect (v) {
          std::cout << "Before size is: " << vect->size () << '\n';
        }
        vector<int> * operator -> () {
          std::cout << "Operator ->* invoked on proxy\n";
          // std::cout << std::stacktrace::current() << '\n';
          return vect;
        }
        ~proxy () {
          std::cout << "After size is: " << vect->size () << '\n';
        }
      private:
        vector <int> * vect;
    };
    VisualizableVector (vector<int> *v) : vect(v) {}    
    proxy operator -> () {
       std::cout << "operator->() invoked on the VisualizableVector\n";
       return proxy (vect);
    }
  private:
    vector <int> * vect;
};

int main()
{
  vector<int> vec;
  VisualizableVector vecc(&vec);
  vecc->push_back(10);
}

This results (GodBolt.org) in:

operator->() invoked on the VisualizableVector
Before size is: 0
Operator ->* invoked on proxy
After size is: 1

How come an operator->() is executed twice, even though I only dereferenced once? Is a pointer supposed to be dereferenced repeatedly until the result is of a non-pointer type, or a non-dereferenceable type?

0

There are 0 best solutions below