Is the following code legal (by C++11 and/or C++14 standard(s))?
#include <iostream>
#include <utility>
using namespace std;
void foo(int &a) {
cout << a << endl;
}
int main() {
foo(reinterpret_cast<int &>(move(5)));
}
- If yes, is it undefined behavior?
- If it's not undefined behavior, can I even mutate
a
insidefoo
without it becoming UB?
It compiles on clang 3.5, not on gcc 4.9. GCC error:
? g++-4.9 -std=c++1y sample.cpp -o sample
sample.cpp: In function 'int main()':
sample.cpp:11:40: error: invalid cast of an rvalue expression of type 'std::remove_reference<int>::type {aka int}' to type 'int&'
foo(reinterpret_cast<int &>(move(5)));
^
EDIT
FYI, a custom made cast that's less hairy than the previous, and which works on C++11 for both GCC and Clang, would be the following lvalue
function:
#include <iostream>
namespace non_std {
template <typename T>
constexpr T &lvalue(T &&r) noexcept { return r; }
}
void divs(int &a, int &b) {
int t = a;
a /= b;
b /= t;
}
int main() {
using namespace std;
using namespace non_std;
int i_care_for_this_one = 4;
divs(i_care_for_this_one, lvalue(2));
cout << i_care_for_this_one << endl;
}
See Question&Answers more detail:os