Nov 6, 2013

[c++][NOTE] size of array with template

Array of size <= 0 is not allowed.

However, when passing array of size 0 to template is allowed
 
ArrayTest<int[0]> at;
_but_, only matches to
 
template<typename T>
struct ArrayTest <T[0]>
{};

Will _not_ matches to:
 
template<typename T, unsigned int N>
struct ArrayTest <T[N]>
{};
new int[] is ok, will still give a pointer point to a memory.

_but_

From 5.3.4/7
When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.

From 3.7.3.1/2
The effect of dereferencing a pointer returned as a request for zero size is undefined.

Even if the size of the space requested [by new] is zero, the request can fail.

That means you can do it, but you can not legally (in a well defined manner across all platforms) dereference the memory that you get
 - you can only pass it to array delete - and you should delete it.

From 3.7.3.1/2
[32. The intent is to have operator new() implementable by calling malloc() or calloc(), so the rules are substantially the same. C++ differs from C in requiring a zero request to return a non-null pointer.]

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.