vendredi 25 décembre 2015

C++11 static cast to rvalue reference

A friend of mine wrote some code similar to this in a 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.y and running the program under Valgrind (which reported a memory error). What I do not understand is why this is even compiling (I am using g++4.9.3). I was actually expecting an error message along the lines of no matching function for call to B::B(A &&). I apologize if this is a stupid remark but how is it essentially different from writing B b = static_cast<B>(a) - which does give me a compile error? The only difference I see is copy from A to B vs move from A to B, and both of them are undefined here.

Thank you in advance for any help.

Aucun commentaire:

Enregistrer un commentaire