title: subscript operator overload returning pointer and assigning value to it
body: <p>I got a situation where I have a <code>class</code> <code>B</code> having a protected <code>array</code> of <code>A*</code>. I have an another function <code>A* func()</code> which returns pointers to <code>A</code> objects stored in some other container. (for example <code>std::map&lt;int,A*&gt;</code> or <code>A* arr[]</code>).</p>
  
  <p>For example the following implementation:</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  class A {
  public:
      A(int _x): x(_x){};
      int x;
  };
  class B{
  public:
      B() {
          this-&gt;arr[0] = new A(1);
          this-&gt;arr[1] = new A(2);
      }
      // use idx to index in to the internal array and return A*
      A*&amp; operator[](int idx); // return reference to pointer to avoid not a lvalue error
  private:
      // class B has this private array of A*
      A* arr[2];
  };
  
  A*&amp; B::operator[](int idx) {
      return this-&gt;arr[idx]; // 0&lt;=idx&lt;=1
  }
  
  
  
  A* arr[2];
  A* func(int x) {
      return arr[x]; // 0&lt;=idx&lt;=1
  }
  
  int main() {
      arr[0] = new A(12);
      arr[1] = new A(14);
  
      B b;
  
      b[1] = func(1); // assign a new value
  
      cout &lt;&lt; b[1]-&gt;x &lt;&lt; endl; // prints 14
  }
  // memory leaks of this program can be removed using `std::shared_ptr&lt;A&gt;` in the place of `A*`.
  </code></pre>
  
  <p>In this example, <code>operator[]()</code> returns a reference to a pointer, because returning pointer becomes <code>rvalue</code> and I will not be able to assign value to it (i.e. <code>b[1] = func(1)</code>). </p>
  
  <p>My question is, is this <code>reference to pointer returning</code> recommended (other ways to achieve this )? or is this perfectly fine with raw pointers as well as with <code>shared_ptr</code>?</p>
  
  <p>Thank You!</p>