首页 > 解决方案 > C ++初始化:无括号与空括号

问题描述

Foo foo;和有什么区别Foo foo{};?(以及为什么用户定义的ctor很重要,如下所示)

我写了一些测试代码,发现当没有提供用户定义的ctor时,Foo foo;会给出一个未初始化的对象,FooFoo foo{};执行零初始化,但是当提供用户定义的ctor时,两者都会给出未初始化的对象。

#include <iostream>

constexpr std::size_t LEN = 10;

struct Foo
{
    Foo() {}  // user-defined ctor, though empty
    int a[LEN];
};

struct Bar
{
    // no user-defined ctor
    int a[LEN];
};

template <typename FooBar>
void print(const FooBar &foobar)
{
    for (int i = 0; i < LEN; ++i) {
        std::cout << foobar.a[i] << ", ";
    }
    std::cout << std::endl;
}

int main()
{
    Foo foo1;
    print(foo1);
    Foo foo2{};
    print(foo2);
    Bar bar1;
    print(bar1);
    Bar bar2{};
    print(bar2);
    return 0;
}

可能的输出(g++10.3、MSYS2、Win10):

-1369499968, 490, -1788275447, 32759, 1, 0, 2, 0, -1369500000, 490,
1, 0, 0, 0, -1788275056, 32759, 24, 0, 0, 0,
-1788275408, 32759, 8, 0, 0, 0, 268501009, 0, -1369503896, 490,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

标签: c++initializationdefault-constructor

解决方案


推荐阅读