Should a move constructor take a const or non-const rvalue reference?

前端 未结 4 968
死守一世寂寞
死守一世寂寞 2020-11-30 03:29

In several places I\'ve seen the recommended signatures of copy and move constructors given as:

struct T
{
    T();
    T(const T& other);
    T(T&&a         


        
4条回答
  •  离开以前
    2020-11-30 03:43

    Should a move constructor take a const or non-const rvalue reference?

    It should take non-const rvalue reference. The rvalue references first of all don't make sense in their const forms simply because you want to modify them (in a way, you want to "move" them, you want their internals for yourself ).

    Also, they have been designed to be used without const and I believe the only use for a const rvalue reference is something very very arcane that Scott Meyers mentioned in this talk (from the time 42:20 to 44:47).

    Am I right in this line of reasoning? That I should stop returning things that are const?

    This is a bit of too general question to answer I reckon. In this context, I think it's worth mentioning that there's std::forward functionality that will preserve both rvalue-ness and lvalue-ness as well as const-ness and it will also avoid creating a temporary as a normal function would do should you return anything passed to it.

    This returning would also cause the rvalue reference to be "mangled" into lvalue reference and you generally don't want that, hence, perfect forwarding with the aforementioned functionality solves the issue.

    That being said, I suggest you simply take a look at the talk that I posted a link to.

提交回复
热议问题