memset在C ++中初始化 [英] memset for initialization in C++
问题描述
memset有时用于在构造函数中初始化数据,如下例所示。它一般工作吗?这是一个好主意吗?
memset is sometimes used to initialize data in a constructor like the example below. 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));
}
推荐答案
c $ c> memset 。这是从C的延期,不会在非POD上工作。具体来说,在包含任何虚函数的派生类或包含非内置函数的任何类中使用它将导致灾难。
Don't use memset
. It's a holdover from C and won't work on non-PODs. Specifically, using it on a derived class that contains any virtual functions -- or any class containing a non-builtin -- will result in disaster.
C ++提供了特定的语法用于初始化:
C++ provides a specific syntax for initialization:
class A {
public:
A();
private:
int a;
float f;
char str[35];
long *lp;
};
A::A()
: a(0), f(0), str(), lp(NULL)
{
}
说实话,我不确定,但 memset
对浮点数也可能是一个坏主意,因为它们的格式未指定。
To be honest, I'm not sure, but memset
might also be a bad idea on floating-points since their format is unspecified.
这篇关于memset在C ++中初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!