What happens to the string data when std::string objects are passed to functions?

I've noticed something I don't understand happening to the string arguments to functions.

I've written this little test program:

#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); } 

I compile it like this:

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

Under g++ 4.2.1 on Mac OSX 10.6, str inside foo() looks the same as it does as hello outside foo():

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 (str=@0x7fff5fbfd350) 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" } } 

Under g++ 4.3.3 on Ubuntu, however, it doesn't:

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`" 

So, what's happening to the value of the string when it is passed to this function? And why the difference between the two compilers?

8

1 Answer

On my compiler foo() is inlined, so there is only one hello. Perhaps that is what is happening for you too.

What a program looks like in a debugger is not part of the language standard. Only the visible result, like actually printing "Hello", is.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like