我注意到了一些我不明白的函數的字符串參數。將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
我剛剛編輯了這個問題,以提供一個可重複的示例,與我的代碼庫脫離。它似乎取決於編譯器。 –