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 #Include Using...
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?
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.