是 C++ 组织的成员吗? struct默认初始化为0?

发布于 2024-07-26 18:23:34 字数 233 浏览 4 评论 0原文

我有这个struct

struct Snapshot
{
    double x; 
    int y;
};

我希望xy为0。默认情况下它们是0还是我必须做:

Snapshot s = {0,0};

什么是将结构归零的其他方法?

I have this struct:

struct Snapshot
{
    double x; 
    int y;
};

I want x and y to be 0. Will they be 0 by default or do I have to do:

Snapshot s = {0,0};

What are the other ways to zero out the structure?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

面犯桃花 2024-08-02 18:23:34

如果不初始化结构体,它们就不为空。

Snapshot s; // receives no initialization
Snapshot s = {}; // value initializes all members

第二个将使所有成员为零,第一个将它们保留为未指定的值。 请注意,它是递归的:

struct Parent { Snapshot s; };
Parent p; // receives no initialization
Parent p = {}; // value initializes all members

第二个将使 ps{x,y} 为零。 如果结构中有构造函数,则无法使用这些聚合初始值设定项列表。 如果是这种情况,您必须向这些构造函数添加适当的初始化,

struct Snapshot {
    int x;
    double y;
    Snapshot():x(0),y(0) { }
    // other ctors / functions...
};

将 x 和 y 都初始化为 0。请注意,您可以使用 x(), y() 来初始化它们,而不管它们的值type:这就是值初始化,通常会产生适当的初始值(0 表示 int,0.0 表示 double,调用具有用户声明构造函数的用户定义类型的默认构造函数,...)。 这很重要,尤其是当您的结构是模板时。

They are not null if you don't initialize the struct.

Snapshot s; // receives no initialization
Snapshot s = {}; // value initializes all members

The second will make all members zero, the first leaves them at unspecified values. Note that it is recursive:

struct Parent { Snapshot s; };
Parent p; // receives no initialization
Parent p = {}; // value initializes all members

The second will make p.s.{x,y} zero. You cannot use these aggregate initializer lists if you've got constructors in your struct. If that is the case, you will have to add proper initalization to those constructors

struct Snapshot {
    int x;
    double y;
    Snapshot():x(0),y(0) { }
    // other ctors / functions...
};

Will initialize both x and y to 0. Note that you can use x(), y() to initialize them disregarding of their type: That's then value initialization, and usually yields a proper initial value (0 for int, 0.0 for double, calling the default constructor for user defined types that have user declared constructors, ...). This is important especially if your struct is a template.

筑梦 2024-08-02 18:23:34

不,默认情况下它们不为 0。 确保所有值或默认为 0 的最简单方法是定义一个构造函数,

Snapshot() : x(0), y(0) {
}

这可确保 Snapshot 的所有使用都具有初始化值。

No, they are not 0 by default. The simplest way to ensure that all values or defaulted to 0 is to define a constructor

Snapshot() : x(0), y(0) {
}

This ensures that all uses of Snapshot will have initialized values.

阳光的暖冬 2024-08-02 18:23:34

一般来说,没有。 但是,在函数中声明为文件作用域或静态的结构将被初始化为 0(就像这些作用域的所有其他变量一样):

int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0

void foo() {
  struct { int a, b; } bar; // undefined
  static struct { int c, d; } quux; // 0, 0
}

In general, no. However, a struct declared as file-scope or static in a function /will/ be initialized to 0 (just like all other variables of those scopes):

int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0

void foo() {
  struct { int a, b; } bar; // undefined
  static struct { int c, d; } quux; // 0, 0
}
仅一夜美梦 2024-08-02 18:23:34

使用 POD,您还可以编写

Snapshot s = {};

You Should not use memset in C++,memset 的缺点是,如果结构中存在非 POD,它将破坏它。

或者像这样:

struct init
{
  template <typename T>
  operator T * ()
  {
    return new T();
  }
};

Snapshot* s = init();

With POD you can also write

Snapshot s = {};

You shouldn't use memset in C++, memset has the drawback that if there is a non-POD in the struct it will destroy it.

or like this:

struct init
{
  template <typename T>
  operator T * ()
  {
    return new T();
  }
};

Snapshot* s = init();
手心的海 2024-08-02 18:23:34

在 C++ 中,使用无参构造函数。 在 C 中,你不能有构造函数,所以使用 memset 或 - 有趣的解决方案 - 指定的初始值设定项:

struct Snapshot s = { .x = 0.0, .y = 0.0 };

In C++, use no-argument constructors. In C you can't have constructors, so use either memset or - the interesting solution - designated initializers:

struct Snapshot s = { .x = 0.0, .y = 0.0 };
混吃等死 2024-08-02 18:23:34

我相信正确的答案是他们的价值观是未定义的。 通常,在运行代码的调试版本时它们会被初始化为 0。 运行发行版本时通常不会出现这种情况。

I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.

ゃ人海孤独症 2024-08-02 18:23:34

由于这是一个 POD(本质上是一个 C 结构),因此以 C 方式初始化它几乎没有什么坏处:

Snapshot s;
memset(&s, 0, sizeof (s));

或者类似地,

Snapshot *sp = new Snapshot;
memset(sp, 0, sizeof (*sp));

我也不会在 C++ 程序中使用 calloc()

Since this is a POD (essentially a C struct) there is little harm in initialising it the C way:

Snapshot s;
memset(&s, 0, sizeof (s));

or similarly

Snapshot *sp = new Snapshot;
memset(sp, 0, sizeof (*sp));

I wouldn't go so far as to use calloc() in a C++ program though.

是伱的 2024-08-02 18:23:34

将 pod 成员移至基类以缩短初始化列表:

struct foo_pod
{
    int x;
    int y;
    int z;
};

struct foo : foo_pod
{
    std::string name;
    foo(std::string name)
        : foo_pod()
        , name(name)
    {
    }
};

int main()
{
    foo f("bar");
    printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}

Move pod members to a base class to shorten your initializer list:

struct foo_pod
{
    int x;
    int y;
    int z;
};

struct foo : foo_pod
{
    std::string name;
    foo(std::string name)
        : foo_pod()
        , name(name)
    {
    }
};

int main()
{
    foo f("bar");
    printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}
早乙女 2024-08-02 18:23:34

我知道这个问题非常老了,但是这个问题在谷歌上突然出现,我找到了另一种方式,并认为我应该在这里添加它:

Snapshot s {};

我不确定这个语法需要什么 C/C++ 语言版本。

I know this question is super old, but this question popped up for me on google and I found this other way and figured I'd add it here:

Snapshot s {};

I'm not sure what C/C++ language version you need for this syntax.

不语却知心 2024-08-02 18:23:34

xy 是否为零取决于您执行的初始化形式。
请注意,您的 struct 是一个 聚合< /a> 因为它没有用户声明的构造函数。

默认初始化

Snapshot snap;

如果聚合有一个隐式定义的默认构造函数(是的,这个有),那么它与执行 每个成员的默认初始化(请参阅 [class.default.ctor] p4)。
换句话说,这将像您(在函数中)编写一样初始化成员:

double x;
int y;

因此,xy不是零初始化除非您还提供默认成员初始值设定项

struct Snapshot
{
    double x = 0; 
    int y = 0;
};

任何其他形式 任何其他形式都会将 x 和 y初始化

为零或其他一些选择值。 这里有些例子:

Snapshot s{};        // value-initialization zeros x and y
Snaphot();           // same
Snapshot{};          // same
Snapshot s = {};     // same; copy-list initialization with value-initializationn
Snapshot s{0, 0};    // aggregate initialization (direct-list-initialization)
Snapshot s = {0, 0}; // aggregate initialization (copy-list-initialization)

Whether x and y are zero depends on the form of initialization you do.
Note that your struct is an aggregate because it has no user-declared constructors.

Default-initialization

Snapshot snap;

If the aggregate has an implicitly-defined default constructor (and yes, this one does), then it's the same as performing default-initialization for each member (see [class.default.ctor] p4).
In other words, this would initialize the members as if you wrote (in a function):

double x;
int y;

Therefore, x and y are not zero-initialized unless you also provide default member initializers:

struct Snapshot
{
    double x = 0; 
    int y = 0;
};

Any other form of initialization

Any other form would either initialize x and y to zero or some other value of choice. Here are some examples:

Snapshot s{};        // value-initialization zeros x and y
Snaphot();           // same
Snapshot{};          // same
Snapshot s = {};     // same; copy-list initialization with value-initializationn
Snapshot s{0, 0};    // aggregate initialization (direct-list-initialization)
Snapshot s = {0, 0}; // aggregate initialization (copy-list-initialization)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文