我注意到了一些我不明白的函数的字符串参数。将std :: string对象传递给函数时,字符串数据会发生什么变化?
我写这个小测试程序:
#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
在G ++ 4.2.1在Mac OSX 10.6,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 ([email protected]) 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"
}
}
在G ++ 4.3.3在Ubuntu上,但是,它并不:
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`"
所以,当它传递给这个函数发生了什么的字符串值?为什么两个编译器之间的区别?
也许堆栈被你的代码的一部分覆盖。 – istudy0
您需要找到一段代码来重现问题。 – Puppy
我刚刚编辑了这个问题,以提供一个可重复的示例,与我的代码库脱离。它似乎取决于编译器。 –