我注意到我不理解函数的字符串参数。
我写过这个小小的测试程序:
#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
在Mac OSX 10.6上的g ++ 4.2.1下,str
中的foo()
与hello
之外的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"
}
}
然而,在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`"
那么,当字符串传递给这个函数时,它的值是怎么回事?为什么两个编译器之间存在差异?
答案 0 :(得分:2)
我的编译器foo()
内联,因此只有一个hello
。也许这就是你正在发生的事情。
调试器中的程序看起来不是语言标准的一部分。只有可见的结果,比如实际打印“Hello”,才是。