1

I have code like this and I am curious if this is safe.

#include <iostream>
struct A{
    int x=4;
    A* operator-(){return this;}    
};
A func(){return A();}

int main(){
    std::cout<<(-func())->x<<std::endl; //Dereferencing to temporary object
    return 0;
}

I compiled it with g++ 6.3.0 with -O3 and it printed 4 as I had expected. I know it wouldn't work if I put the result of -func() in a new variable and dereferenced it later, but in the above case, is the result guaranteed?

cpplearner
  • 13,776
  • 2
  • 47
  • 72
eivour
  • 1,678
  • 12
  • 20

0 Answers0