1

When overloading operator ->, one would eventually have to return a pointer. If this pointer points to an object created inside the function like:

struct Something {
  char c;
  Something(char k){
    c = k;
  }
};
struct Hello {
  int a;
  Something* operator->(){
    Something s(a);
    return &s;
  }
};

Would then dereferencing this result in undefined behavior (as Can a local variable's memory be accessed outside its scope?):

Hello h {5};
cout << h->c;

If so, can this be resolved, still using operator->?

1 Answers1

1

Would then dereferencing this result in undefined behavior?

Yes.

If so, can this be resolved, still using operator->?

The following applies to any other member function.

Create Something instance as a member of Hello. Then the pointer to it remains valid for the duration of Hello's lifetime. You can construct Something from the integer you are storing immediately, so you can get rid of it.

If Something takes additional resources (memory, handles, etc.), you probably want to construct it at the time of operator-> call. You can choose std::unique_ptr (dynamic) or std::optional (static) for this. Or, if Something supports an uninitialized state (e.g. default-constructed), you can initialize (e.g. move-assign) to it later.


If you cannot alter Hello class then your only option is to overload operator-> to return by Something by value directly.

But, I must say, the circumstances of this problem are starting to get weird and the way of overloading operators even more so.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74