Correct usage of rvalue references as parameters

前端 未结 5 1956
孤城傲影
孤城傲影 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条回答
  •  温柔的废话
    2020-12-04 09:56

    Since we know most of the time the Path is a temporary rvalue, does it make sense to add an Rvalue version of this method?

    Probably not... Unless you need to do something tricky inside Load() that requires a non-const parameter. For example, maybe you want to std::move(Path) into another thread. In that case it might make sense to use move semantics.

    Is this a correct approach to writing rvalue versions of methods?

    No, you should do it the other way around:

    void Asset::load( const std::string& path )
    {
         auto path_copy = path;
         load(std::move(path_copy)); // call the below method
    }
    void Asset::load( std::string&& path )
    {
        // complicated method....
    }
    

提交回复
热议问题