g**********1 发帖数: 1113 | 1 If I use memset in the constructor of a class as follows
#include
#include
class A {
public:
A()
{
memset(this, 0,sizeof(*this));
}
virtual void test()const
{}
private:
};
int main()
{
A A1;
A * A2=new A;
A1.test(); //not crash here.
A2->test();//crash here.
return 0;
}
I know memset will set VPTR to be NULL but I do not know why If I do not use
new, A1.test() can be called properly. |
z****e 发帖数: 2024 | 2 怎么又来了,
不是不crash就没事,因为undefined, 什么都可能发生。
这个红猪侠解释的比较好。
我的一点愚见,因为vptr木有了,dereference 一个木有了的指针显然不行。
但是 concrete object 可能没事,因为不动用dynamic binding, 不查vtable,不调vptr。故而,一个普通函数在栈上调用而已。
这个要大牛来确认。我不知道C++ under the hood,因为木有时间看了。。。。
面试被问这种,就认栽了。 |
g**********1 发帖数: 1113 | 3 I was asked in the interview but only asked me why memset is not good. I
told them the problem with the VPTR but I try to compile some code with
concrete object. It works but after I get it address and defer it with *, it
does not works. I believe some happens with the concrete call. It should
not call the virtual through VPTR. I wonder what it calls. |
g**********1 发帖数: 1113 | 4 It seems that A1.test() calls the test() at compile time and (&A1)->test()
calls at run time. I am not sure.
Thank you guys. |
z****e 发帖数: 2024 | 5 我不是说过了吗?
一个是static binding, 不用调vptr,没事
一个是dynamic binding,要用vptr,但是vptr木有了,。。。
【在 g**********1 的大作中提到】 : It seems that A1.test() calls the test() at compile time and (&A1)->test() : calls at run time. I am not sure. : Thank you guys.
|
h****8 发帖数: 599 | 6 A1.test()和A2->test()调用的都是同一个函数virtual test()
不同的是,对这个函数的地址的解析。
对于A1.test(),在编译的时候编译器已经确定了函数地址
对于A2->test(),需要在runtime,通过vptr来找到函数地址。然而vptr已经是空指针,
所以runtime出错
it
【在 g**********1 的大作中提到】 : I was asked in the interview but only asked me why memset is not good. I : told them the problem with the VPTR but I try to compile some code with : concrete object. It works but after I get it address and defer it with *, it : does not works. I believe some happens with the concrete call. It should : not call the virtual through VPTR. I wonder what it calls.
|
g**********1 发帖数: 1113 | 7 Thank you and got it. :) |