Antonin
Antonin

Reputation: 119

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.

Upvotes: 4

Views: 367

Answers (1)

user743382
user743382

Reputation:

A static_cast from an lvalue of type A to B && can be valid:

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

The conversion is available, is not rejected by the compiler, because it could under other circumstances be valid. Yes, you're right, in your case it's definitely not valid.

I was actually expecting an error message along the lines of no matching function for call to B::B(A &&).

You would get an error along those lines (but not exactly that) if you used std::move(a). By not having to spell out the type, it reduces the possibility of errors.

Upvotes: 5

Related Questions