简体   繁体   English

c++11 - 默认初始化的成员的零初始化

[英]c++11 - zero-initi of members insted of default-init

In the below code, I expect members of a being inited with gargabe as they are not mentioned in the members-init-list of the called constructor (with two int parameters).在下面的代码中,我希望使用 gargabe 初始化a的成员,因为在被调用的构造函数的成员初始化列表中没有提到它们(带有两个int参数)。 Instead, I'm constantly getting 0 in both i and j of a , b and c and I am failing to see why.相反,我在abcij中不断得到0 ,我不明白为什么。 Could anybody please point me in the right direction?有人可以指出我正确的方向吗?

#include <iostream>
#include <type_traits>


class A {
    public:
        int i;
        int j;
        A() = delete;
        A(int a, int b) { std::cout << "VOLOLO!" << std::endl; };
};

int
smear_stack(int p)
{
    int j = p++;
    int a[500] = {};
    for(int i = 0; i < 499; i++) {
        a[i] = ++j;
    }
    std::cout << j << std::endl;
    return ++j;
}

int main(void)
{
    int i = 2;
    i = smear_stack(++i);

    A a  (i, 32 );
    std::cout << "a is " << a.i << " " << a.j << std::endl;

    A b = { a };
    std::cout << "b is " << b.i << " " << b.j << std::endl;

    A c = { a.i, a.j };
    std::cout << "c is " << c.i << " " << c.j << std::endl;
}

The i and j fields that you are accessing are, indeed, uninitialized.您正在访问的ij字段实际上是未初始化的。 However, you are smearing the wrong part of the stack.但是,您涂抹了堆栈的错误部分。 It just so happens that on most OSes, the stack is initially all zeros.碰巧的是,在大多数操作系统上,堆栈最初都是零。 It even used to be common in C (long ago) to assume that automatic variables in main were zero-initialized.在 C(很久以前)中甚至曾经很常见假设main中的自动变量是零初始化的。

To see that the memory is indeed uninitialized, it suffices to put something else there.要查看 memory 确实未初始化,只需将其他内容放在那里就足够了。 Here's an example:这是一个例子:

#include <iostream>
#include <memory>

class A {
public:
    int i;
    int j;
    A() = delete;
    A(int a, int b) { std::cout << "VOLOLO!" << std::endl; };
};

union U {
    int is[2];
    A a;
    U() : is{3,4} {}
};

int
main()
{
    U u;
    std::construct_at(&u.a, 5, 6);
    std::cout << u.a.i << ", " << u.a.j << std::endl;
    // output:
    // VOLOLO!
    // 3, 4
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM