【问题标题】:C++ - gdb gives unexpected output when passing in a struct with std::string memberC++ - gdb 在传入带有 std::string 成员的结构时给出了意外的输出
【发布时间】:2016-03-29 08:45:39
【问题描述】:

考虑以下程序,我使用g++ -g myprog.cc 编译它。

#include<iostream>

struct Context {
    //char *s; // version 1
    std::string s; // version 2
};

void f(Context);
void f(Context c) {}

int main(void) {
    Context c = Context();
    f(c);
}

版本 1 有一个 char * 成员,而版本 2 将其替换为 std::string

使用 gdb,我单步执行代码并得到:

临时断点 1,myprog.cc:12 处的 main()
12 上下文 c = 上下文();
&ebsp;缺少单独的调试信息,使用:debuginfo-install libgcc-4.4.7-11.el6.x86_64 libstdc++-4.4.7-11.el6.x86_64
(gdb) s
13 f(c);
(gdb) s
f (c=...) 在 myprog.cc:9
9 void f(上下文 c) {}
(gdb) s
main () 在 myprog.cc:14
14 }

这里没有错。

如果我单步执行第 2 版,我会得到:

临时断点 1,myprog.cc:12 处的 main()
12 上下文 c = 上下文();
缺少单独的调试信息,请使用:debuginfo-install libgcc-4.4.7-11.el6.x86_64 libstdc++-4.4.7-11.el6.x86_64
(gdb) s
上下文::上下文 (this=0x7ffffffffe400) 在 myprog.cc:3
3 结构上下文 {
(gdb) s
main () 在 myprog.cc:13
13 f(c);
(gdb) s
上下文::上下文 (this=0x7ffffffffe410) 在 myprog.cc:3
3 结构上下文 {
(gdb) s
f (c=...) 在 myprog.cc:9
9 void f(上下文 c) {}
(gdb) s
上下文::~上下文 (this=0x7ffffffffe410, __in_chrg=) 在 myprog.cc:3
3 结构上下文 {
(gdb) s
上下文::~上下文 (this=0x7ffffffffe400, __in_chrg=) 在 myprog.cc:3
3 结构上下文 {
(gdb) s
main () 在 myprog.cc:14
14 }

为什么当我传入带有std::string 成员的结构Context 时,会得到输出Context::Context (this=0x7fffffffe400)

另外,当我实例化结构时,this=0x7fffffffe400。当我传递它时,this=0x7fffffffe410。这是为什么呢?

【问题讨论】:

    标签: c++ gdb


    【解决方案1】:

    您将c 按值传递给不执行任何操作的函数。所以编译器必须产生传值语义的任何可见效果。编译器无法确定复制然后销毁 string 没有任何后果,所以它会这样做。可以肯定的是,复制char *并销毁该副本没有任何后果,因此不麻烦。

    【讨论】:

      【解决方案2】:

      发生的事情是您看到编译器生成的构造函数,它不是为仅使用指针的结构生成的,因为在该构造函数中将无事可做。对于具有std::string 成员的结构,它可能会调用std::strings 构造函数。

      由于构造函数是一个非静态成员函数,this=0x7fffffffe400 是传入的隐式“this”指针参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-07
        • 1970-01-01
        • 2016-03-11
        • 2020-07-05
        • 1970-01-01
        • 2013-12-20
        • 2013-09-11
        • 2013-07-15
        相关资源
        最近更新 更多