gpt4 book ai didi

c++ - 具有 C++ 虚函数时的 GDB 不完整类型

转载 作者:搜寻专家 更新时间:2023-10-31 01:01:14 27 4
gpt4 key购买 nike

我刚刚注意到一些奇怪的事情,当我在我的类(除构造函数之外的任何函数)中添加“virtual 关键字”时,我无法在 GDB 中显示我的对象的内容。 GDB 说“类型不完整”

代码如下:

///////////////reco.h/////////////

#ifndef RECO_H
#define RECO_H

#include <iostream>
#include <string>

class reco {
public:
reco(float weight);
~reco(void);

float getWeight();

private:
float weight;
};

#endif

////////////////reco.cpp/////////////

#include <iostream>
#include <string>

#include "reco.h"

using namespace std;

reco::reco(float weight) {
weight = weight;
}

reco::~reco(void) {
cout << "destructor reco" << endl;
}

float reco::getWeight() {
return weight;
}

/////////////main.cpp////////////

#include <iostream>
#include <string>

#include "reco.h"

using namespace std;


int main() {
reco* s = new reco(5.0);
cout << s->getWeight() << endl;

delete s;

return 0;
}

然后使用 GDB:

gdb main.exe
breakpoint main.cpp:11 <---- (cout)
run
print *s
$1 = { weight = 5 }

然后,如果我将其中一个函数设置为“虚拟”,我将重试打印我的 *s GDB的指针,它说:“不完整类型”

看起来 VTABLE 发生了一些事情,好像“virtual”关键字隐藏了我的 Reco 类的实现。我知道编译器会进行后期绑定(bind),然后 VTABLE 查找在运行时完成,但是当 GDB 调试程序时程序已经在运行,对吗?

“设置打印vtbl”设置为“开”。

如果我使用 ptype s , 我得到 <incomplete type>再次留言。

如果我用 x/540f80 检查地址,它说“无法访问内存”

我不知道为什么只添加这个关键字会使我的对象的类型不完整?

非常感谢您的帮助!

我注意到的最后一件事:

虚拟:

 reco.cpp -> g0 and main.cpp -> g = incomplete type
reco.cpp -> g and main.cpp ->g = ok

没有虚拟

 reco.cpp -> g0 and main.cpp -> g = ok
reco.cpp -> g and main.cpp ->g = ok

最佳答案

reco.cpp -> g and main.cpp ->g = ok

假设 -> g 你的意思是你用 -g 标志编译 reco.cpp,是的 do 那,不要 这样做:

g++ -c -g0 reco.cpp

您发现 GCC 可以优化它必须发出的调试信息的数量如果它知道您有一个 key method .

没有virtual,就没有关键方法,GCC 必须向每个 编译单元发送冗余 调试信息。这会使您的目标文件更大(它应该对最终的可执行文件影响很小或没有影响),但允许您进行调试,即使只有部分目标文件是使用调试信息编译的。

关于c++ - 具有 C++ 虚函数时的 GDB 不完整类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29494132/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com