10

我经常在代码中遇到手动零初始化的 POD 结构,memset如下所示:

struct foo;
memset(&foo, 0, sizeof(foo));

我检查了 C++11 标准,它说:“初始化器是一组空括号的对象,即 (),应进行值初始化。” 其次是: “对类型 T 的 [pod 结构] 进行值初始化意味着……对象被零初始化。”

那么...这是否意味着您始终可以安全地将上述代码压缩为以下内容:

struct foo{};

并且有一个保证初始化的结构,就好像你已经调用了memset(&foo, 0, ...)


如果是这样,那么一般来说,您可以使用空初始化程序安全地初始化任何东西,如下所示:

SomeUnknownType foo{};  // will 'foo' be completely "set" to known values?

我知道这在 C++03 中并不总是可能的(在统一初始化语法之前),但现在在 C++11 中对于任何类型都有可能吗?

4

2 回答 2

10

You can certainly initialize any standard layout type using empty parenthesis and get it zero initialized. Once you add constructors into the picture, this isn't necessarily true, unfortunately:

struct foo {
    int f;
};
struct bar {
    int b;
    bar() {}
};

foo f{};
bar b{};

While f.f is zero initialized, b.b is uninitialized. However, there isn't anything you can do about bar because you can't memset() it either. It needs to be fixed.

于 2013-08-17T02:35:22.613 回答
3

Memset will initialize it to 0 but empty parenthesis will value initialze your object(there is a difference).

Quoting from the standard:

To value-initialize an object of type T means:

  • if T is a class type with a user-declared constructor, then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

Also, doing struct foo{}; is safe and it takes care of not reseting the virtual table pointer.

But doing memset(&foo, 0, sizeof(foo)); in case of virtual functions is really really bad as it resets the pointer to the virtual table.

于 2013-08-17T02:34:03.560 回答