Why are C++0x rvalue reference not the default?

后端 未结 2 826
不知归路
不知归路 2020-12-24 02:43

One of the cool new features of the upcoming C++ standard, C++0x, are "rvalue references." An rvalue reference is similar to an lvalue (normal) reference, except t

2条回答
  •  臣服心动
    2020-12-24 03:42

    Because adding a new kind of reference allows you to write two overloads of a method:

    void CopyFrom(MyClass &&c)
    {
        dataMember.swap(c);
    }
    
    void CopyFrom(const MyClass &c)
    {
        dataMember.copyTheHardWay(c);
    }
    

    The version that accepts the new kind of reference is allowed to modify the variable it receives, because that variable isn't going to be used anywhere else. So it can "steal" the contents of it.

    This is the whole reason this feature was added; retaining one type of reference wouldn't achieve the desired goal.

提交回复
热议问题