在C中,为了确保所有结构都归零,我用以下命令包装malloc:
void* safe_malloc(size_t size){
void *result = malloc(size);
memset(result, 0, size); //NULL check ommitted for brevity
return result;
}这样我就可以避免做以下事情:
struct Foo {
int bar;
int bat;
};
struct Foo *tmp = malloc(sizeof(struct Foo));
tmp->bar = 0;
tmp->bat = 0; // I want to avoid this laundry list of initializers我想为C++做一些类似的事情,我希望一个类的所有成员都被初始化为零,就像Java语言中自动完成的那样。使用像C解决方案这样的解决方案会出现两个问题: 1.你不能清除vtable ptr;2.一个子类将清除继承的成员值。
class Foo {
public:
int bar;
int bat;
Foo(int bar){
this->bar = bar;
this->bat = 0; // I dont want to explicitly have to initialize this here
}
}
class Baz : public Foo {
public:
int bam;
Baz(int bar, int bam) : Foo(bar) {
this->bam = bam;
}
}如何避免在C++中出现等同的洗衣单?
发布于 2014-04-23 13:21:50
https://stackoverflow.com/questions/23235271
复制相似问题