1

我想要一个按值返回字符串的函数,并且我想从该返回值构造另一个字符串。当调用 NRVO/RVO 时,移动构造器工作正常,没有复制,但是当我不能依赖 NRVO 时,即使我明确移动返回值,该函数也会复制字符串。

我打印原始数据地址的值以检查是否制作了副本。

这是代码:

void printStringAdr(const std::string& s)
{
    std::cout << (void*)s.data() << std::endl;
}

std::string getStringNRVO() 
{
    std::string str("text");
    printStringAdr(str);
    return str; //works fine, no copy
}

std::string getStringNoNRVO() 
{
    std::string str1("ABC");
    std::string str2("XYZ");

    if (rand() % 2)
    {
        printStringAdr(str1);
        return str1; //makes copy
    }
    else
    {
        printStringAdr(str2);
        return str2; //makes copy
    }
}

std::string getStringNoNRVO_ForceMove()
{
    std::string str1("ABC");
    std::string str2("XYZ");

    std::string* strptr = &str1;

    if (rand() % 2)
        strptr = &str2;

    printStringAdr(*strptr);
    return std::move(*strptr); //doesn't work, makes copy
}


int main()
{
    std::string s = getStringNRVO(); //only this function works like i expect
    printStringAdr(s);
}
4

0 回答 0