2011-06-20 25 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()'没有为我内联。 –

相关问题