简体   繁体   中英

passing string by value vs passing every character by value

void func(char c) {}
void func(std::string) {}

int main() {
    std::string s("HelloWorld");

    // method 1
    func(s);

    // method 2
    for(std::size_t i = 0; i < s.size(); i++) {
        func(s[i]);
    }
}

why is passing by value in case of the second call OK? is it not effectively copying the same number of characters in the end? Or are they actually the same and I'm missing something?

The copy of std::string will do an allocation (unless small string optimization), whereas passing char as parameter would probably be done by register.

Pass std::string by const reference

void func(const std::string&);

Passing every character of a string by value to a function is just as not-okay as passing the entire string by value. That is, in both cases you should prefer some alternative, where the entire string doesn't have to be copied or traversed, if you can.

Passing a single character by value is OK because the size of a character is less than the size of a pointer you need to pass by reference. Plus, no copy constructors are invoked for a character.

(That does not mean calling a function for each character in a string is always OK)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM