2011-06-20 26 views
0

我注意到了一些我不明白的函數的字符串參數。將std :: string對象傳遞給函數時,字符串數據會發生什麼變化?

我寫這個小測試程序:

#include <string> 
#include <iostream> 

using namespace std; 

void foo(string str) { 
    cout << str << endl; 
} 

int main(int argc, char** argv) { 
    string hello = "hello"; 
    foo(hello); 
} 

我編譯它是這樣的:

$ g++ -o string_test -g -O0 string_test.cpp 

在G ++ 4.2.1在Mac OSX 10.6,strfoo()看起來一樣它爲hellofoo()

12 foo(hello); 
(gdb) p hello 
$1 = { 
    static npos = 18446744073709551615, 
    _M_dataplus = { 
    <std::allocator<char>> = { 
     <__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, 
    members of std::basic_string<char,std::char_traits<char>,std::allocator<char> >::_Alloc_hider: 
    _M_p = 0x100100098 "hello" 
    } 
} 
(gdb) s 
foo ([email protected]) at string_test.cpp:7 
7  cout << str << endl; 
(gdb) p str 
$2 = (string &) @0x7fff5fbfd350: { 
    static npos = 18446744073709551615, 
    _M_dataplus = { 
    <std::allocator<char>> = { 
     <__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, 
    members of std::basic_string<char,std::char_traits<char>,std::allocator<char> >::_Alloc_hider: 
    _M_p = 0x100100098 "hello" 
    } 
} 

在G ++ 4.3.3在Ubuntu上,但是,它並不:

12   foo(hello); 
(gdb) p hello 
$1 = {static npos = 18446744073709551615, _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x603028 "hello"}} 
(gdb) s 
foo (str={static npos = 18446744073709551615, _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x7fff5999e530 "(0`"}}) at string_test.cpp:7 
7   cout << str << endl; 
(gdb) p str 
$2 = {static npos = 18446744073709551615, _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x7fff5999e530 "(0`"}} 
(gdb) p str->_M_dataplus->_M_p 
$3 = 0x7fff5999e530 "(0`" 

所以,當它傳遞給這個函數發生了什麼的字符串值?爲什麼兩個編譯器之間的區別?

+0

也許堆棧被你的代碼的一部分覆蓋。 – istudy0

+3

您需要找到一段代碼來重現問題。 – Puppy

+0

我剛剛編輯了這個問題,以提供一個可重複的示例,與我的代碼庫脫離。它似乎取決於編譯器。 –

回答

2

在我的編譯器foo()是內聯的,所以只有一個hello。也許這也是你正在發生的事情。

程序在調試器中看起來像什麼不是語言標準的一部分。只有可見的結果,如實際打印「你好」,是。

+2

這也可能是副本進行小字符串內聯存儲優化,GDB不知道小字符存儲 – bdonlan

+0

這聽起來像它可能是答案。 'foo()'沒有爲我內聯。 –

相關問題