2

While a normal overload of the arrow operator typically returns a plain pointer, as cppreference.com notes, it doesn't have to:

The overload of operator -> must either return a raw pointer, or return an object (by reference or by value) for which operator -> is in turn overloaded.

When the operator returns an object by value, what is the lifetime of that object?

Naively, I could imagine two different ways of it working. Either the returned object is lifetime preserved until the statement is complete, or the returned temporary is "discarded" immediately after the subsequent operator-> is called on it.

For example:

class A {
    class A_sub {
         A_sub(...);
         int foo();
    }

    std::unique_ptr< A_sub > operator->() {
        return std::make_unique< A_sub >(...);
    }
}

int main() {
    A a;
    int val = A->foo();
    return val;
}

When is the destructor for A_sub permitted to be called? Is it prior to the call to foo(), or is the returned unique_ptr lifetime preserved until foo() completes? (Does it depend on deep the drill down behavior goes?)

It seems to me that the "obvious" answer would be that all operator-> return values would be preserved until the ultimate completion of the statement (due to lifetime issues as demonstrated above), but I'm unsure if the C++ standard guarantees such ordering.

R.M.
  • 3,461
  • 1
  • 21
  • 41

0 Answers0