简体   繁体   中英

Prevent default construction of array elements

element* elements = new element[size.x];

This will build X elements with the default constructor. 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= ?

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.

explicit vector ( 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:

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:

elements * e = new elements[2] { elements(1,2,3), elements('a', true) };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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