Taking address of a temporary is allowed if the function's result is consumed [duplicate]

16 hours ago 1
ARTICLE AD BOX

I work in Visual Studio, and observe that a function taking a const pointer can be called with a pointer on temporary conditionally depending on the usage of function's result.

The minimal example that I could reduce from my code is as follows:

struct B { virtual ~B() {} }; struct A : B {}; A foo(const B*) { return {}; } A bar() { return {}; } int main() { //foo(&bar()); //error auto v = foo(&bar()); //ok in MSVC }

Here the simple call foo(&bar()) results in the error:

C2102: '&' requires l-value

And the longer auto v = foo(&bar()); line is fine for MSVC. Online demo

Is the second line is indeed permitted in C++, while the first one is not?

Read Entire Article