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

后端 未结 13 1987

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:16

    Unless you actually need a copy it's still reasonable to take const &. For example:

    bool isprint(std::string const &s) {
        return all_of(begin(s),end(s),(bool(*)(char))isprint);
    }
    

    If you change this to take the string by value then you'll end up moving or copying the parameter, and there's no need for that. Not only is copy/move likely more expensive, but it also introduces a new potential failure; the copy/move could throw an exception (e.g., allocation during copy could fail) whereas taking a reference to an existing value can't.

    If you do need a copy then passing and returning by value is usually (always?) the best option. In fact I generally wouldn't worry about it in C++03 unless you find that extra copies actually causes a performance problem. Copy elision seems pretty reliable on modern compilers. I think people's skepticism and insistence that you have to check your table of compiler support for RVO is mostly obsolete nowadays.


    In short, C++11 doesn't really change anything in this regard except for people that didn't trust copy elision.

提交回复
热议问题