H*****L 发帖数: 5705 | 1 memset is sometimes used to initialize data in a constructor like the
example below.
Q: What is the benefit of initializing this way? Does it work in this
example? Does it work in general ? Is it a good idea in general?
class A {
public:
A();
private:
int a;
float f;
char str[35];
long *lp;
};
A::A()
{
memset(this, 0, sizeof(*this));
} |
z****e 发帖数: 2024 | 2 不推荐这样做。
my answers:
1.What is the benefit of initializing this way?
efficiency.
2.Does it work in this example?
yes.
3.Does it work in general ?
gut feeling is "not quite". but i can not come up with an example to
demonstrate.
4.Is it a good idea in general?
absolutely not.
because:
if there is any virtual pointer, which is initialized right after the
execution enters the left open brace { of the constructor, memset will clear
the virtual pointer and polymorphism calls will be invalid. |
t****t 发帖数: 6806 | 3
didn't you come up with the example in 4?
【在 z****e 的大作中提到】 : 不推荐这样做。 : my answers: : 1.What is the benefit of initializing this way? : efficiency. : 2.Does it work in this example? : yes. : 3.Does it work in general ? : gut feeling is "not quite". but i can not come up with an example to : demonstrate. : 4.Is it a good idea in general?
|
z****e 发帖数: 2024 | 4 师傅,你看这个行吗?
class B{
public:
virtual void call()=0;
virtual ~B()=0;
};
B::~B(){}
class D:public B{
public:
D(){
memset(this,0,sizeof(*this));
}
virtual void call(){
cout<<"D::call()"<
}
};
int main(int argc, char* argv[ ]){
B* b=new D;
b->call();//undefined behavior
} |
z****e 发帖数: 2024 | 5 不过有一点没有理解,
好像如果不是虚函数,没有继承,自己调用成员函数不会错。
好像,this指针,所指向内容,并没有清零。
不知道为什么
memset(this,0,sizeof(*this));
不把this指针所指向内容也给清零了?
this->regular_member_function();
好像是对的。 |
t****t 发帖数: 6806 | 6
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
正确
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
从上一句怎么得到这一句的?
【在 z****e 的大作中提到】 : 不过有一点没有理解, : 好像如果不是虚函数,没有继承,自己调用成员函数不会错。 : 好像,this指针,所指向内容,并没有清零。 : 不知道为什么 : memset(this,0,sizeof(*this)); : 不把this指针所指向内容也给清零了? : this->regular_member_function(); : 好像是对的。
|
z***e 发帖数: 5393 | 7 成员函数只是global function改了名字而已,this->regular_member_func()其实会变
成$asdfasr2_safawr2_regular_member_func(Your_Class* p, ...)之类的。
但是vptb呢?memset的话,vptb就完蛋了吧?
【在 z****e 的大作中提到】 : 不过有一点没有理解, : 好像如果不是虚函数,没有继承,自己调用成员函数不会错。 : 好像,this指针,所指向内容,并没有清零。 : 不知道为什么 : memset(this,0,sizeof(*this)); : 不把this指针所指向内容也给清零了? : this->regular_member_function(); : 好像是对的。
|