beginpluses
beginpluses

Reputation: 537

static_cast int to reference to int?

Is it allowed:

int x = 1;
int r1 = static_cast<int&>(x);
int r2 = static_cast<int&&>(x)

If it is, then what is the meaning of these casts?

The question has arisen from this code:

int x = 1;
int y = 2;
std::swap(x, y); // uses int temp = std::move(x);

Upvotes: 0

Views: 393

Answers (2)

eerorika
eerorika

Reputation: 238341

static_cast int to reference to int? Is it allowed

Yes. It is allowed.

If it is, then what is the meaning of these casts?

Casting to lvalue reference of same type is mostly pointless, since a variable used by itself is already an lvalue. However, it can affect decltype deduction as shown in Ben Voigt's example. Casting to a reference to another type is useful if you need to downcast a reference to base (which is not relevant to int).

Casting to rvalue reference is useful, since it changes the type of the expression into xvalue. This allows moving from variables. This is in fact what std::move does. This doesn't make a difference with int in particular though.

Upvotes: 7

Quimby
Quimby

Reputation: 19113

static_cast<int&>(x);

Doesn't do anything as x is already of type int& when used in expression.

static_cast<int&&>(x);

Casts x, an l-value, to r-value. This is exactly what std::move does and T&& are used for implementing move semantics.

std::swap uses std::move because there's simply no downside and probable performance boost. Move ctors/assignments should always be at least as efficient as copy ctors/assignments.

Upvotes: 1

Related Questions