在gdb:C ++的帮助下探索类对象创建

时间:2014-05-04 09:03:53

标签: c++ gdb

考虑下面的代码,我写了:

#include <iostream>
#include <cstring>
#include <cstdlib>



using namespace std;

class employee{
int ID;
char* name;

        public:

employee(int id,const char* ptr);
~employee();
int getID();
char* getName();
};

employee::employee(int id,const char* ptr):ID(id){
        name= (char*) malloc((strlen(ptr)+1)*sizeof(char));
        strcpy(name,ptr);
        cout << "Employee with ID : " << ID << " Name : " << name << " constructed." << endl;
}

employee::~employee(){
        cout << "Employee with ID : " << ID << " Name : " << name << " destructed." << endl;
        free(name);
        name=NULL;
}

int employee::getID(){return ID;}
char* employee::getName(){return name;}


int main()
{
 employee Ob1(145645,"Edward Collins");
 cout << "Employee Details:" << endl;
 cout << "ID: " << Ob1.getID() << " Name : " << Ob1.getName() << endl;


return 0;
}

输出结果为:

$ g++ -g -Wall GDB.cpp -o GDB


$ ./GDB
Employee with ID : 145645 Name : Edward Collins constructed.
Employee Details:
ID: 145645 Name : Edward Collins
Employee with ID : 145645 Name : Edward Collins destructed.

现在我想找出存储Ob1, Ob1.ID, Ob1.name, Ob1.getID(), Ob1.getName()的地址:

$ gdb GDB
(gdb) break 39
Breakpoint 1 at 0x4012f5: file GDB.cpp, line 39.
(gdb) run


Breakpoint 1, main () at GDB.cpp:39
39       employee Ob1(145645,"Edward Collins");
(gdb) s
employee::employee (this=0x22abf8, id=145645, ptr=0x4020b8 <_data_start__+184> "Edward Collins") at GDB.cpp:21
21      employee::employee(int id,const char* ptr):ID(id){
(gdb)

我可以看到this指针为0x22abf8,即位置0x22abf8正在创建Ob1。 我试过如下:

Breakpoint 1, main () at GDB.cpp:39
39       employee Ob1(145645,"Edward Collins");
(gdb) s
employee::employee (this=0x22abf8, id=145645, ptr=0x4020b8 <_data_start__+184> "Edward Collins") at GDB.cpp:21
21      employee::employee(int id,const char* ptr):ID(id){
(gdb) s
22              name= (char*) malloc((strlen(ptr)+1)*sizeof(char));
(gdb) s
23              strcpy(name,ptr);
(gdb) s
24              cout << "Employee with ID : " << ID << " Name : " << name << " constructed." << endl;
(gdb) print &ID
$1 = (int *) 0x22abf8
(gdb) x/d 0x22abf8
0x22abf8:       145645
(gdb) print &name
$2 = (char **) 0x22abfc
(gdb) x/d 0x22abfc
0x22abfc:       537103464
(gdb) info locals
No locals.
(gdb)

基本上我可以看到ID的地址;但我想找出构造对象的类成员的所有地址,并希望在gdb的帮助下探索how an class object is being constructed inside memory即地址Ob1,Ob1.ID, Ob1.name, Ob1.getID(), Ob1.getName()

可以帮助吗?

0 个答案:

没有答案