In the past I was taught that when passing std::string
to a function or even a constructor to pass by const reference
instead of passing by value due to copy.
example 1: - function parameter
void someFunc( const std::string& str1, const std::string& str2 ) {
// some code
}
example 2: - constructor argument
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
};
With modern C++
we now have move semantics; I'm not 100% sure for function parameters as of yet but I'm guessing they should relatively be the same as class constructor arguments: And Foo from above simply becomes:
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
};
Are there specific cases where one method is favored over the other; or should the old way of being taught pass string as const reference
now be discarded and just use pass by direct object and use move semantics
instead? If so what is the overall trade offs or benefits of the later over the previous way of doing things in C++
? If not, then what's the point of new features such as move semantics? Or does it depend on individual situations? Mainly looking for some definitive clarity.
I do believe that the 2nd case of Foo
should at the least fulfill RAII
and that is not what I'm pertaining to either.