Correct usage of rvalue references as parameters

前端 未结 5 1958
孤城傲影
孤城傲影 2020-12-04 08:59

Let\'s take the following method as an example:

void Asset::Load( const std::string& path )
{
    // complicated method....
}

General u

5条回答
  •  萌比男神i
    2020-12-04 09:55

    If your Load member function doesn't assign from the incoming string, you should simply provide void Asset::Load(const std::string& Path).

    If you do assign from the incoming path, say to a member variable, then there's a scenario where it could be slightly more efficient to provide void Asset::Load(std::string&& Path) too, but you'd need a different implementation that assigns ala loaded_from_path_ = std::move(Path);.

    The potential benefit is to the caller, in that with the && version they might receive the free-store region that had been owned by the member variable, avoiding a pessimistic delete[]ion of that buffer inside void Asset::Load(const std::string& Path) and possible re-allocation next time the caller's string is assigned to (assuming the buffer's large enough to fit its next value too).

    In your stated scenario, you're usually passing in string literals; such caller's will get no benefit from any && overload as there's no caller-owned std::string instance to receive the existing data member's buffer.

提交回复
热议问题