C++ 当std::string对象传递给函数时,字符串数据会发生什么变化?
我注意到函数的字符串参数发生了一些我不理解的事情 我编写了这个小测试程序:C++ 当std::string对象传递给函数时,字符串数据会发生什么变化?,c++,C++,我注意到函数的字符串参数发生了一些我不理解的事情 我编写了这个小测试程序: #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); } 在
#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);
}
在Mac OSX 10.6上的g++4.2.1下,str
内部foo()
与hello
外部foo()
看起来一样:
12foo(你好);
(gdb)p你好
$1 = {
静态NPO=18446744073709551615,
_M_dataplus={
= {
= {}, },
std::basic_string::_Alloc_hider的成员:
_M_p=0x100100098“你好”
}
}
(gdb)s
字符串测试处的foo(str=@0x7fff5fbfd350)。cpp:7
我的编译器上的7 cout是内联的foo()
,因此只有一个hello
。也许这也是你正在经历的事情
调试器中的程序不是语言标准的一部分。只有可见的结果,如实际打印“Hello”,是。可能堆栈被代码的某些部分覆盖。您需要找到重现问题的代码部分。我刚刚编辑了问题,以给出一个与我的代码库分离的可重现示例。它似乎取决于编译器。为什么您认为您有问题?只要函数打印“Hello”,那么为什么大量内部数据实际显示的内容很重要呢?请查看basic_string
的两种实现的源代码,并参阅。库实现者为目标编译器设计了许多专门的优化。如果我猜的话,有一个小字符串优化正在进行,而这个成员并没有做你认为它做的事情。但谁能确定呢?库。也有可能副本进行了小字符串内联存储优化,GDB不知道小字符串存储,这听起来可能是答案<代码>foo()
没有为我内联。
$ g++ -o string_test -g -O0 string_test.cpp
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"
}
}
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`"