I don't know whether I am asking a good question, but I am really curious about this. Everything except for this new r-value reference introduced in C++, I can translate and understand in C terms. Not everyone would agree with me but to me, C++ is a highly sophisticated C macro extension.
Okay, what I want to know here is that, for example if you look at constructors and destructors as follows,
{
struct Object {
char* s;
Object(size_t n) { s = new char[n]; }
~Object() { delete[] s; }
} o(10);
}
you can expect the compiler to handle the code as if,
{
struct Object { char* s; } o;
new_Object(&o, 10); /* o->s = malloc(10); */
delete_Object(&o); /* free(o->s); */
}
I'm not saying the C++ compiler has to do this translation. I just believe that C++ was designed to work this way, in order to integrate smoothly with existing C applications and attract C developers.
Anyway, a plain l-value reference can be understood as, and is most likely to actually be, an abstracted pointer. To the compiler it should be same with,
int n = 1;
int& m = n;
m = 2;
and
int n = 1;
int* m = &n;
*m = 2;
But what about r-value references? Can anyone explain how r-value references and std::move
could be understood in C terms?
It's the same as an lvalue reference except that it can only bind to rvalues.
An example might be:
typedef struct S { int x; } S;
S foo() { S s; return s; }
S && r = foo();
C equivalent of the last line might be:
S *p = &(foo());
except that C has a rule that you cannot apply &
to rvalues , and also that the return value of a function call does not persist past the end of the statement with the function call.
So you would have to write something like:
S temp = foo();
S *p = &temp;