我应该如何从C ++正确初始化C结构? [英] How should I properly initialize a C struct from C++?

查看:81
本文介绍了我应该如何从C ++正确初始化C结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++文件中有以下代码:

I have the following code in a C++ file:

#include <sys/socket.h>

// ...
void someFunc() {
    struct msghdr msg = {0};  // <<< Uninitialized member here
}

当我使用 g ++编译时使用 -Wall -Wextra ,我收到警告:

When I compile with g++ using -Wall -Wextra, I get warnings:

error: missing initializer for member 'msghdr::msg_namelen'
...same for several other fields

我的问题是:我无法显式初始化所有字段,因为我不知道结构msghdr 。该结构没有默认的构造函数,因为它是C结构。我的印象是 = {0} 格式导致所有字段都为零初始化(这对我来说很好),但是 g ++ 错误消息提示没有。

My problem is this: I can't explicitly initialize all the fields, because I don't know what fields will exist (cross-platform) in a struct msghdr. The struct doesn't have a default constructor, since it's a C struct. I was under the impression that the = {0} form led to zero-initialization of all fields (which would be fine for me), but the g++ error message suggests not.

我在这里有什么选择?

推荐答案

void someFunc()
{
    msghdr msg = {};  // <<< All members zero-initialized
}

g ++ -Wextra 警告级别对恕我直言不是很有用。

The g++ -Wextra warning level is IMHO not very useful.

对于 C struct,您所拥有的代码也正式可用,即标准POD (普通旧数据)。但是您的代码会用0显式初始化第一个成员。这对于非POD的汇总(例如以 std :: string 作为第一位成员,而纯粹的 {} 对此也适用。

The code that you have is also formally OK for a "C struct", in standardeese known as POD (Plain Old Data). But your code explicitly initializes first member with 0. That won't necessarily work for an aggregate that isn't POD, e.g. with a std::string as first member, while the pure {} will work also for that.

顺便说一句,像您正在处理的POD一样,通常具有第一个成员的字节数,然后您就可以像…

In passing, often a POD like the one you're dealing with has a byte count as first member, and then you can do like …

void foo()
{
    SomePODStruct o = {sizeof(o)};    // The other members zero-initialized.
}

也许添加 STATIC_ASSERT

Perhaps add a STATIC_ASSERT that the byte count member is first (at offset 0).

干杯& hth。,

Cheers & hth.,

这篇关于我应该如何从C ++正确初始化C结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆