其他分享
首页 > 其他分享> > C 11是否保证一个垂死的物体会被移动而不是复制为一个参数?

C 11是否保证一个垂死的物体会被移动而不是复制为一个参数?

作者:互联网

#include <vector>

using namespace std;

void f(const vector<int>&) {}
void f(vector<int>&&) {}

int main()
{
    {
        vector<int> coll;

        //
        // coll is dying, so,
        // "f(coll)" will call "f(const vector<int>&)" or
        // "f(vector<int>&&)" as per C++11?
        //
        f(coll); 
    }
}

在上面的代码中,coll正在消亡;那么,f(coll)将根据C 11调用f(const vector< int>&)或f(vector< int>&&)?

解决方法:

如果f(coll)调用f(vector< int>&&)而不是f(const vector< int>&)那将违反标准,因为它会选择错误的函数重载.

如果呼叫的分辨率根据呼叫的位置以及在使用coll的呼叫之后是否有任何后续语句而有所不同,那么它也会相当混乱.

特殊待遇仅限于return values

If expression is an lvalue expression and the conditions for copy elision are met, or would be met, except that expression names a function parameter, then overload resolution to select the constructor to use for initialization of the returned value is performed twice: first as if expression were an rvalue expression (thus it may select the move constructor or a copy constructor taking reference to const), and if no suitable conversion is available, overload resolution is performed the second time, with lvalue expression (so it may select the copy constructor taking a reference to non-const).

标签:c,c11,move-semantics,standards,language-design
来源: https://codeday.me/bug/20190828/1753497.html