[英]Prevent default construction of array elements
element* elements = new element[size.x];
This will build X elements with the default constructor. 这将使用默认构造函数构建X元素。 During my program, I would like to construct each element with different constructor parameters, like this: 在我的程序期间,我想用不同的构造函数参数构造每个元素,如下所示:
for(int i=0; i < size.x; ++i)
elements[i] = element(i);
Is there any way to prevent and needless default instanciation (that I don't want to implement) and a needless calle to Operator=
? 有什么方法可以防止不必要的默认实例化(我不想实现)以及对Operator=
的不必要的被调用?
if it doesn't hurt your design you can use a double pointer to achieve this 如果不损害您的设计,则可以使用双指针来实现
element ** elements = new element * [size.x];
for(int i=0; i < size.x; ++i)
elements[i] = new element(i);
Well, if this is really a problem for you, don't use an array. 好吧,如果这对您来说确实是一个问题,请不要使用数组。 Use a std::vector
with the default constructor. 使用默认构造函数的std::vector
。
explicit vector ( const Allocator& = Allocator() ); 显式向量(const Allocator&= Allocator()); Default constructor: constructs an empty vector, with no content and a size of zero. 默认构造函数:构造一个空向量,不包含任何内容,大小为零。
You can copy -initialize automatic arrays, which will usually be optimized out to straight in-place construction, with a brace initializer: 您可以复制 -initialize自动数组,通常使用括号初始化器将其优化为直接就地构造:
elements e[] = { elements(1,2,3), elements(), elements('a', true) };
That does not work for dynamic arrays, though. 但是,这不适用于动态数组。 In C++11 you can specify an initializer list, but that too is copy-initialization, not direct initialization: 在C ++ 11中,您可以指定一个初始化列表,但这也是复制初始化,而不是直接初始化:
elements * e = new elements[2] { elements(1,2,3), elements('a', true) };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.