2010-10-11 105 views
11

如果在該函數中完成的所有操作都是爲了複製該字符串,我應該總是通過const引用將std :: string傳遞給函數嗎?另外,按值傳遞和按引用傳遞之間有什麼區別(性能或其他)?據我所知,一個使用operator=和其他複製構造函數。是這樣嗎?我應該如何將std :: string傳遞給函數?

+3

當您通過引用傳遞時,不會進行復制。當你傳值時,使用複製構造函數。 – Anycorn 2010-10-11 05:23:10

回答

19

如果在函數內部完成的所有工作都是複製該字符串,我是否應該總是通過const引用將std :: string傳遞給函數?

不。如果您打算只複製函數內的字符串,您應該傳遞值。這允許編譯器執行幾個優化。欲瞭解更多信息,請閱讀Dave Abraham的"Want Speed? Pass by Value."

傳遞值和傳遞參考之間有什麼區別(perf或其他)?據我所知,一個使用operator =和另一個拷貝構造函數。是這樣嗎?

不,這並非如此。參考不是一個對象;它是對一個對象的引用。當您按值傳遞時,會傳遞一個正在傳遞的對象的副本。當您通過引用傳遞時,會對現有對象進行引用,並且沒有副本。 A good introductory C++ book將詳細解釋這些基本概念。如果您想用C++開發軟件,理解基礎知識至關重要。

+0

我認爲這取決於他通過製作副本的意思。如果是成員,那麼它應該作爲參考被傳遞並且被複制到成員。在C++ 0x中,通過值和'std :: move'將它轉換爲成員。 – GManNickG 2010-10-11 05:34:04

+0

而不是使用std :: move當你不能/不使用C++時,你可以使用swap方法(或std :: swap)來獲得類似的行爲0x – Grizzly 2010-10-11 13:52:17

+0

是否有編譯器和例子的組合通過價值傳遞的代碼實際上表現更好?我想知道。 – 2010-10-13 21:01:45

27

不要相信你在互聯網上閱讀的所有東西。最好通過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 

通過引用傳遞更快一個數量級。

+0

謝謝,我會自己試試:) – nakiya 2010-10-13 07:12:59

+1

在Visual Studio 2012中: 「foo花費了3701個週期 bar花費了1110個週期」 – nergeia 2014-01-22 12:02:54

+0

在x86_64上使用g ++ 4.8.1我得到4130與1820.差距正在縮小。 – 2014-03-19 14:41:54

相關問題