Understanding rvalue references

后端 未结 5 880
清歌不尽
清歌不尽 2020-12-15 19:03

I think there\'s something I\'m not quite understanding about rvalue references. Why does the following fail to compile (VS2012) with the error \'foo\' : cannot conver

5条回答
  •  春和景丽
    2020-12-15 19:23

    Why does it get transformed into int once inside the function body?

    It doesn't; it's still a reference to an rvalue.

    When a name appears in an expression, it's an lvalue - even if it happens to be a reference to an rvalue. It can be converted into an rvalue if the expression requires that (i.e. if its value is needed); but it can't be bound to an rvalue reference.

    So as you say, in order to bind it to another rvalue reference, you have to explicitly convert it to an unnamed rvalue. std::forward and std::move are convenient ways to do that.

    Also, why not std::move?

    Why not indeed? That would make more sense than std::forward, which is intended for templates that don't know whether the argument is a reference.

提交回复
热议问题