请看一下我的源文件,它们太长了,不能在这里发布:
X11Painter.cpp: <a href="http://pastebin.com/gu4SrHUr" rel="noreferrer noopener nofollow">http://pastebin.com/gu4SrHUr</a>
X11Painter.h: <a href="http://pastebin.com/3ktp1Fvn" rel="noreferrer noopener nofollow">http://pastebin.com/3ktp1Fvn</a>
这个类的行为在我看来非常奇怪。
我有以下测试用例:
#include "X11Painter.h"
int main()
{
X11Painter p ;
p.show();
}
用行编译它
g++ -O0 -g -o test2 test2.cpp X11Painter.cpp -lX11 -lXfixes -lXinerama
简单地运行它会执行以下操作:
this->some_test=1234
this->screen:0
1:: this->display='0x8b73008'; this->window='77594625'
width: 3200
0xbff91bdc
this->some_test=1234
this->some_test=3682292
Segmentation fault
我正在尝试在 X11Painter::show()
中映射 X11 窗口
当我开始调查为什么 X11Painter.cpp:83 是段错误时,我发现大多数变量在 show()
中被覆盖并且完全不同。比他们在构造函数中。
我把 int some_test
看看发生了什么。为什么值会发生变化?
如果我这样做 printf("%p\n", this)
,指针也发生变化。我怀疑在某个地方,这个指针被覆盖了。但是为什么会这样呢?使用 ddd 进行调试告诉我 this->some_value 在退出构造函数时被修改。
使用测试类(具有公共(public)构造函数、一个公共(public)方法和一个私有(private)变量的类)进行简短测试没有任何问题。
有人知道为什么会发生这种奇怪的事情吗? 我知道堆栈中的变量会发生什么,但我们仍然在 main 中......
它可能与 X11 库有关吗?
最佳答案
在你的无参数构造函数中,你这样做
X11Painter::X11Painter()
{
X11Painter(-1);
}
这并不是您认为的那样,因为 C++ 中没有构造函数链接。上面的代码所做的是构造一个临时的 X11Painter
对象,为该临时对象调用另一个构造函数,但实际上并未初始化您要构造的对象中的任何内容。
要解决此问题但保留相同的行为,请删除无参数构造函数并在 .h
文件中将另一个构造函数声明为
X11Painter(int screenno = -1);
如果您不提供参数,这会将 screenno
参数默认为 -1
。
关于C++: 这个指针被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4417072/