我为什么要提供默认构造函数? [英] Why do I have to provide default ctor?
问题描述
为什么要提供默认的构造函数,如果我要创建我的类型的对象的数组?
感谢您的答案
Why do I have to provide default ctor if I want to create an array of objects of my type? Thanks for answers
推荐答案
由于他们已被初始化。
考虑一下,如果这是不是这样的:
Consider if it wasn't the case:
struct foo
{
foo(int) {}
void bar(void) {}
};
foo a[10];
foo f = a[0]; // not default-constructed == not initialized == undefined behavior
请注意你不这样做的有无的为:
Note you don't have to:
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)};
}
如果你真的需要一个对象数组,你不能给一个有意义的默认构造函数,使用的std ::矢量
。
如果你确实需要的对象的数组,不能给一个有意义的默认构造函数,的和的希望留在栈中,你需要懒洋洋地初始化的对象。 <一href=\"http://stackoverflow.com/questions/2187246/how-to-avoid-successive-deallocations-allocations-in-c\">I写这样一个实用工具类。 (你会使用的第二个版本,第一个使用动态内存分配。)
If you really need an array of of objects, can't give a meaningful default constructor, and want to stay on the stack, you need to lazily initialize the objects. I have written such a utility class. (You would use the second version, the first uses dynamic memory allocation.)
例如:
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
这篇关于我为什么要提供默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!