开发者

How should I pass a std::string to a function?

开发者 https://www.devze.com 2023-01-19 23:08 出处:网络
Should I always pass a std::string by const reference to a function if all that is done inside that function is to copy that string? Additionally, what is the difference (perf or otherwise) between pa

Should I always pass a std::string by const reference to a function if all that is done inside that function is to copy that string? Additionally, what is the difference (perf or otherwise) between passing by valu开发者_开发问答e and passing by reference? As I understand, one uses operator= and the other copy constructor. Is that the case?


Don't believe everything you read on the internet. It is better to pass by const reference. To give proof, I wrote a test program...

test.cpp:

#include <ctime>
#include <iostream>
#include <string>

void foo(std::string s);
void bar(const std::string& s);

int main() {
    const std::string s("test string");

    clock_t start = clock();
    for (int it = 0; it < 1000000; ++it)
        foo(s);
    std::cout << "foo took " << (clock() - start) << " cycles" << std::endl;

    start = clock();
    for (int it = 0; it < 1000000; ++it)
        bar(s);
    std::cout << "bar took " << (clock() - start) << " cycles" << std::endl;
}

aux.cpp:

#include <string>
std::string mystring;

void foo(std::string s) { mystring = s; }
void bar(const std::string& s) { mystring = s; }

Compiled with 'g++ -O3 test.cpp aux.cpp' and got the printout:

foo took 93044 cycles
bar took 10245 cycles

Passing by reference is faster by an order of magnitude.


Should I always pass a std::string by const reference to a function if all that is done inside that function is to copy that string?

No. If you are going to just copy the string inside of the function, you should pass by value. This allows the compiler to perform several optimizations. For more, read Dave Abraham's "Want Speed? Pass by Value."

What is the difference (perf or otherwise) between passing by value and passing by reference? As I understand, one uses operator= and the other copy constructor. Is that the case?

No, that is not at all the case. A reference is not an object; it is a reference to an object. When you pass by value, a copy of the object being passed is made. When you pass by reference, a reference to the existing object is made and there is no copy. A good introductory C++ book will explain these basic concepts in detail. It is critical to understand the basics if you want to develop software in C++.

0

精彩评论

暂无评论...
验证码 换一张
取 消