Conversation
|
Great! There is also similar solution: const X& x = (i == 0)? (const X&)X0() : (i == 1)? (const X&)X1() : (const X&)X2(); pX = const_cast<X*>(&x); |
|
I need to say that those solutions are relying on undefined-ish behavior (casting X0&& to X&& and retaining the ownership) and not every compiler accepts them (see GCC). |
|
It seems that it is not yet fixed in GCC. Explanation why it should work: These are introduced in C++ 11 (all compilers support it): Then this should and works as well in all compilers: Then this should work, because there is no difference from the above (but it only works in the latest Clang 8.0.0): Then: Then: And finally: In VS 17 it works only with |
|
so you think this is actually a bug in GCC? as curiosity: I implemented a small PoC for |
|
Yes, if my conclusions are correct, it is a bug in GCC, and also because it is fixed in Clang 8.0.0 and especially because of https://twitter.com/isocpp/status/1039615649759211520, post from Richard Smith :-) |
|
Attaching interesting info, seems like expression trees using rvalues (in general) are badly supported in GCC: |
|
The problem with gcc shows up without r-value references as well. For the following code snippet {
const X& x = (const X0&) X0();
std::cout << "1" << std::endl;
}
std::cout << "2" << std::endl;BTW: Casting away |
|
Agree with the The problem in GCC starts when casting rvalue ( |
Demo: https://wandbox.org/permlink/3nP8jjoktHTsuqQl