I'm implementing some C++ static analysis rules, and one of them prohibits a function from returning a reference or pointer to a reference parameter of the function, i.e. the following are all non-compliant:

int *f(int&amp; x) { return &amp;x; } // #1
const int *g(const int&amp; x) { return &amp;x; } // #2
int&amp; h(int&amp; x) { return x; } // #3
const int&amp; m(const int&amp; x) { return x; } // #4


The justification given for this is that "It is implementation-defined behaviour whether the reference parameter is a temporary object or a reference to the parameter."

I'm puzzled by this, however, because stream operators in C++ are written in this way, e.g.

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const X&amp; x) {
    //...
    return os;
}


I think I'm pretty confident that stream operators in C++ do not in general exhibit implementation-defined behaviour, so what's going on?

According to my understanding as it is at present, I would expect #1 and #3 to be well-defined, on the basis that temporaries cannot be bound to non-const references, so int&amp; x refers to a real object that has lifetime beyond the scope of the function, hence returning a pointer or reference to that object is fine. I would expect #2 to be dodgy, because a temporary could have been bound to const int&amp; x, in which case trying to take its address would seem a bad plan. I'm not sure about #4 - my gut feeling is that that's also potentially dodgy, but I'm not sure. In particular, I'm not clear on what would happen in the following case:

const int&amp; m(const int&amp; x) { return x; }
//...
const int&amp; r = m(23);



Question: Are there English equivalents to the Japanese saying, “There’s a god who puts you down as well as a god who picks you up”?
Answer: Sometimes You Eat The Bear, Sometimes The Bear Eats You

(The quote from one great movie to lighten down this solemn thread.)