C ++ 11 static rvalue reference

My friend wrote code similar to this project:

struct A {
  int x{0};
};

struct B : public A {
  int y{1};
};

int main() {
  A a;
  B b = static_cast<B &&>(a);
}

IMO, this code is clearly flawed, and I confirmed it by trying to access b.yand run the program under Valgrind (which reported a memory error). I do not understand why this is even compilation (I use g ++ 4.9.3). I really expected an error message in the lines no matching function for call to B::B(A &&). I apologize if this is a stupid remark, but how is it significantly different from writing B b = static_cast<B>(a)- what gives me a compilation error? The only difference I see is copying from Ato Bvs to move from Ato B, and both of them are undefined here.

+4
source share
1

A static_cast lvalue A to B && :

B b;
A &a = b;
B b2 = static_cast<B &&>(a);

, , . , , .

no matching function for call to B::B(A &&).

std::move(a), ( ). , .

+5

Source: https://habr.com/ru/post/1621698/


All Articles