简体   繁体   English

当std :: string对象传递给函数时,字符串数据会发生什么变化?

[英]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() : 在Mac OSX 10.6上的g ++ 4.2.1下, foo()内部的str看起来与foo()外面的hello相同:

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: 但是,在Ubuntu的g ++ 4.3.3下,它没有:

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? 为什么两个编译器之间存在差异?

On my compiler foo() is inlined, so there is only one hello . 在我的编译器上foo()是内联的,所以只有一个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. 只有可见的结果,比如实际打印“Hello”,才是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM