Passing parameter when creating object array

Kirk McDonald kirklin.mcdonald at gmail.com
Tue Aug 7 14:35:23 PDT 2007


Deewiant wrote:
> Kirk McDonald wrote:
> 
>>Using new on a dynamic array type already allows you to pass something
>>looking like a constructor call:
>>
>>auto a = new int[](50); // An array of 50 elements
>>
>>It might be appropriate to add a second, optional parameter to this
>>constructor, with the array's default initializer:
>>
>>auto b = new int[](50, 5); // An array of 50 5s
>>
> 
> 
> This syntax is already taken, for allocating nested arrays:
> http://www.digitalmars.com/d/expression.html#NewExpression
> 

It could still work. Nested (or un-nested) dynamic array types would 
have two constructors: The existing ones, for defining the size of the 
array, and one with one additional argument, defining the default 
initializer of the innermost array's elements.

Therefore:

new char[][](10) // allocate an array of 10 strings
new char[][](10, 20) // allocate 10 strings of 20 \0 characters
new char[][](10, 20, 'a') // allocate 10 strings of 20 'a's.

But now I'm having trouble understanding another part of that page:

"If there is a new ( ArgumentList ), then those arguments are passed to 
the class or struct specific allocator function after the size argument."

For classes, saying 'new C[](20)' creates an array of 20 class 
/references/, set to null, and the class's allocator is never called.

For structs, it is not the structs themselves being new'ed. A struct's 
allocator overload is used when you say 'new S', which returns an S*. 
Saying 'new S[](20)' will create an array whose size in bytes is 
S.sizeof * 20. The struct's allocator has nothing to do with it.

Creating an array of type S*[] has basically the same issue as an array 
of class references: The pointers are initialized to null, and the 
struct's allocator is never called.

Therefore, this line in the spec appears to be useless, and my 
new(false) suggestion could still work.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list