2

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.

Francis Cugler
  • 7,788
  • 2
  • 28
  • 59
  • https://stackoverflow.com/questions/10231349/are-the-days-of-passing-const-stdstring-as-a-parameter-over ; looked also at the linked/related questions – Mat Jun 03 '18 at 04:37
  • @Mat The link to the question was fairly close; and I got a very good dose of mixed answers, reviews, suggestions and guidelines from it; so I'm back to square one by not having a definitive clarity... lol – Francis Cugler Jun 03 '18 at 04:59
  • 2
    You get a lot of different answers because there isn't one option that is always better than the others. Depends on your use cases. (And as always: use the simplest thing first. If it's a bottleneck, investigate and go for more complicated things.) – Mat Jun 03 '18 at 05:18
  • 1
    https://youtu.be/_nrly6PH6NU?t=1m37s – Taekahn Jun 03 '18 at 05:26

0 Answers0