为什么我必须提供默认的ctor?

The*_* do 2 c++ arrays

如果我想创建一个我的类型的对象数组,为什么我必须提供默认的ctor?谢谢你的回答

GMa*_*ckG 8

因为它们必须被初始化.

考虑是不是这样:

struct foo
{
    foo(int) {}

    void bar(void) {}
};

foo a[10];
foo f = a[0]; // not default-constructed == not initialized == undefined behavior
Run Code Online (Sandbox Code Playgroud)

注意:您不具备到:

int main(){
   // initializes with the int constructor
   foo a[] = {1, 2, 3};
}

// if the constructor had been explicit
int main(){
   // requires copy-constructor
   foo a[] = {foo(1), foo(2), foo(3)};
}
Run Code Online (Sandbox Code Playgroud)

如果您确实需要一个对象数组,并且无法提供有意义的默认构造函数,请使用std::vector.

如果你真的需要一个对象数组,不能给出一个有意义的默认构造函数,并且想要留在堆栈中,你需要懒惰地初始化对象.我写了这样一个实用类.(您将使用第二个版本,第一个使用动态内存分配.)

例如:

typedef lazy_object_stack<foo> lazy_foo;

lazy_foo a[10]; // 10 lazy foo's

for (size_t i = 0; i < 10; ++i)
{
    // create a foo, on the stack, passing `i` to the constructor
    a[i].create(i); 
}

for (size_t i = 0; i < 10; ++i)
    a[i].get().bar(); // and use it

// automatically destructed, of course
Run Code Online (Sandbox Code Playgroud)

  • +1用于用户名(和答案,但这是次要的) (5认同)
  • @atch:是的,"GMan - 拯救独角兽"非常肯定,就像我一样:) (3认同)