Are the days of passing const std::string & as a parameter over?

后端 未结 13 1984

I heard a recent talk by Herb Sutter who suggested that the reasons to pass std::vector and std::string by const & are largely gon

13条回答
  •  感动是毒
    2020-11-22 17:17

    Short answer: NO! Long answer:

    • If you won't modify the string (treat is as read-only), pass it as const ref&.
      (the const ref& obviously needs to stay within scope while the function that uses it executes)
    • If you plan to modify it or you know it will get out of scope (threads), pass it as a value, don't copy the const ref& inside your function body.

    There was a post on cpp-next.com called "Want speed, pass by value!". The TL;DR:

    Guideline: Don’t copy your function arguments. Instead, pass them by value and let the compiler do the copying.

    TRANSLATION of ^

    Don’t copy your function arguments --- means: if you plan to modify the argument value by copying it to an internal variable, just use a value argument instead.

    So, don't do this:

    std::string function(const std::string& aString){
        auto vString(aString);
        vString.clear();
        return vString;
    }
    

    do this:

    std::string function(std::string aString){
        aString.clear();
        return aString;
    }
    

    When you need to modify the argument value in your function body.

    You just need to be aware how you plan to use the argument in the function body. Read-only or NOT... and if it sticks within scope.

提交回复
热议问题