通过const引用传递或使用移动语义

时间:2018-06-03 04:20:57

标签: c++ parameter-passing move c++17 move-semantics

在过去,我被教导过将std::string传递给函数或构造函数以传递const reference而不是传递由于复制而导致的值。

示例1: - 功能参数

void someFunc( const std::string& str1, const std::string& str2 ) {
    // some code
}

示例2: - 构造函数参数

class Foo {
private:
    std::string str1_;
    std::string str2_;

public:
    Foo( const std::string& str1, const std::string& str2 ) :
      str1_( str1 ),
      str2_( str2 ),
    {}

    // other methods or functions
};

现代C++我们现在有移动语义;我现在还不是100%确定函数参数,但我猜它们应该与类构造函数参数相同:而且上面的Foo变成了:

class Foo {
private:
    std::string str1_;
    std::string str2_;

public:
    Foo( std::string str1, std::string str2 ) :
      str1_ { std::move( str1 ) },
      str2_ { std::move( str2 ) }
    {}

    // other methods or functions
};

是否存在一种方法优于另一种方法的具体情况;或者现在应该放弃旧的教学方式pass string as const reference并仅使用直接对象传递并使用move semantics代替?如果是这样的话,那么在C++中以前做事的方式的总体权衡或好处是什么?如果没有,那么移动语义等新功能的重点是什么?或者它取决于个别情况?主要是寻找明确的清晰度。

我确实认为Foo的2 nd 案例至少应该履行RAII,而这不是我与之相关的事情。

0 个答案:

没有答案
相关问题