I have two structs struct A
and struct B
with the same memory layout, and I want to cast a return value of type struct A
to type struct B
, for example, in C++, I can achieve this goal in single line (without any temporary variable) like this:
#include <utility>
struct Temp {
int a;
int b;
};
struct MyTemp {
int a;
int b;
};
struct Temp get_temp(int a, int b) {
struct Temp temp = {
.a = a,
.b = b,
};
return temp;
}
int main() {
struct MyTemp mt = reinterpret_cast<MyTemp &&>(std::move(get_temp(1, 2)));
}
However, I can’t find an equivalent in C, foe example, the following code in C does not compile:
void *test = &test;
struct Temp {
int a;
int b;
};
struct MyTemp {
int a;
int b;
};
struct Temp get_temp(int a, int b) {
struct Temp temp = {
.a = a,
.b = b,
};
return temp;
}
int main() {
struct MyTemp mt = *(struct MyTemp *)&get_temp(1, 2);
// error: cannot take the address of an rvalue of type 'struct Temp'
}
So my question is, is there any way to do the same thing I did in C++? If there’s not, why? And why can std::move
bypass this trouble?
You need to sign in to view this answers
Leave feedback about this