1

MyString ret在以下方法中不执行 NRVO 。默认构造的 MyString ( return {};) 直接构造到目标中, ret 被移动构造到目标中。

MyString MyString::Substring(size_type idx, size_type length)
{
    size_type thisSize{ getSize() };
    if (thisSize - idx < length)
    {
        return {};
    }
    
    MyString ret{ length + 1 };
    for (size_type otherIdx{ 0 }; otherIdx < length; ++otherIdx)
    {
        ret[otherIdx] = (*this)[idx + otherIdx];
    }
    ret[length] = '\0';
    return ret;
}

如果在其主体中MyString ret{length + 1};的 if 语句之上return{};,我会很清楚为什么它不能直接构造到目标中:如果是,则返回默认构造的 MyString 对象,销毁ret将是必需的,并且默认构造的对象将取代它。这是不可取的。但是,在这种情况下,MyString ret不能直接构造到目标中的根本原因是什么?在代码中构造时,众所周知该函数不会return {};.

我确定我在这里忽略了一些东西。任何帮助是极大的赞赏!

编辑:这是@rustyx 建议的最小可重复示例:

#include <iostream>

class Foo
{
public:
    Foo() = default;

    Foo(Foo&&) { std::cout << "Moved" << std::endl; }
};

Foo func(int i)
{
    if (i < 0)
    {
        return {};
    }
    Foo bar;
    return bar;
}
int main()
{
    Foo test{ func(-1) };
    Foo test1{ func(1) };
}

这打印:

(Nothing)
Moved
4

0 回答 0