如果一个函数内部只是复制字符串,那么我是否应该总是将std::string以const引用的形式传递给函数?另外,按值传递和按引用传递之间有什么区别(性能或其他方面)?据我所知,一个使用operator=
,另一个使用复制构造函数。是这样吗?
如果一个函数内部只是复制字符串,那么我是否应该总是将std::string以const引用的形式传递给函数?另外,按值传递和按引用传递之间有什么区别(性能或其他方面)?据我所知,一个使用operator=
,另一个使用复制构造函数。是这样吗?
不要轻信互联网上的一切。最好使用const引用进行传递。为了证明这一点,我编写了一个测试程序...
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; }
使用'g++ -O3 test.cpp aux.cpp'编译并得到输出:
foo took 93044 cycles
bar took 10245 cycles
按引用传递速度比按值传递快一个数量级。
foo
的主体应该像这样:mystring = ::std::move(s)
。我认为您会发现在这种情况下结果大不相同。 - Ken Wayne VanderLinde如果函数内部只是复制字符串,我是否应该始终通过const引用传递std :: string?
不需要。如果您只是在函数内部复制字符串,则应该按值传递。这允许编译器执行几个优化。要了解更多信息,请阅读Dave Abraham的“想要加速吗?按值传递。”。
按值传递和按引用传递之间有什么区别(性能或其他方面)?据我所知,一个使用operator =,另一个使用复制构造函数。是这样吗?
不是这样的。引用不是对象;它是对对象的引用。当按值传递时,将复制要传递的对象。当按引用传递时,将创建对现有对象的引用,并且不会进行复制。一本好的C ++入门书将详细解释这些基本概念。如果您想在C ++中开发软件,则理解基础知识至关重要。
std::move
将其移动到成员变量中。 - GManNickG