title: What happens to the string data when std::string objects are passed to functions?
body: <p>I've noticed something I don't understand happening to the string arguments to functions.</p>
  
  <p>I've written this little test program:</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  void foo(string str) {
    cout &lt;&lt; str &lt;&lt; endl;
  }
  
  int main(int argc, char** argv) {
    string hello = "hello";
    foo(hello);
  }
  </code></pre>
  
  <p>I compile it like this:</p>
  
  <pre><code>$ g++ -o string_test -g -O0 string_test.cpp
  </code></pre>
  
  <p>Under g++ 4.2.1 on Mac OSX 10.6, <code>str</code> inside <code>foo()</code> looks the same as it does as <code>hello</code> outside <code>foo()</code>:</p>
  
  <pre><code>12    foo(hello);
  (gdb) p hello
  $1 = {
    static npos = 18446744073709551615, 
    _M_dataplus = {
      &lt;std::allocator&lt;char&gt;&gt; = {
        &lt;__gnu_cxx::new_allocator&lt;char&gt;&gt; = {&lt;No data fields&gt;}, &lt;No data fields&gt;}, 
      members of std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;::_Alloc_hider: 
      _M_p = 0x100100098 "hello"
    }
  }
  (gdb) s
  foo (str=@0x7fff5fbfd350) at string_test.cpp:7
  7     cout &lt;&lt; str &lt;&lt; endl;
  (gdb) p str
  $2 = (string &amp;) @0x7fff5fbfd350: {
    static npos = 18446744073709551615, 
    _M_dataplus = {
      &lt;std::allocator&lt;char&gt;&gt; = {
        &lt;__gnu_cxx::new_allocator&lt;char&gt;&gt; = {&lt;No data fields&gt;}, &lt;No data fields&gt;}, 
      members of std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;::_Alloc_hider: 
      _M_p = 0x100100098 "hello"
    }
  }
  </code></pre>
  
  <p>Under g++ 4.3.3 on Ubuntu, however, it doesn't:</p>
  
  <pre><code>12            foo(hello);
  (gdb) p hello
  $1 = {static npos = 18446744073709551615, _M_dataplus = {&lt;std::allocator&lt;char&gt;&gt; = {&lt;__gnu_cxx::new_allocator&lt;char&gt;&gt; = {&lt;No data fields&gt;}, &lt;No data fields&gt;}, _M_p = 0x603028 "hello"}}
  (gdb) s
  foo (str={static npos = 18446744073709551615, _M_dataplus = {&lt;std::allocator&lt;char&gt;&gt; = {&lt;__gnu_cxx::new_allocator&lt;char&gt;&gt; = {&lt;No data fields&gt;}, &lt;No data fields&gt;}, _M_p = 0x7fff5999e530 "(0`"}}) at string_test.cpp:7
  7           cout &lt;&lt; str &lt;&lt; endl;
  (gdb) p str
  $2 = {static npos = 18446744073709551615, _M_dataplus = {&lt;std::allocator&lt;char&gt;&gt; = {&lt;__gnu_cxx::new_allocator&lt;char&gt;&gt; = {&lt;No data fields&gt;}, &lt;No data fields&gt;}, _M_p = 0x7fff5999e530 "(0`"}}
  (gdb) p str-&gt;_M_dataplus-&gt;_M_p
  $3 = 0x7fff5999e530 "(0`"
  </code></pre>
  
  <p>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?</p>