Site Archive (Complete)
C++ Blog: Why doesn't new return a reference?
C++
void main(void)

Calls, Returns and In-Between.

by Kevin Carlson
SELECTIVE IGNORANCE

Finding the Signal in the Noise

by Andrew Koenig
April 23, 2007

Why doesn't new return a reference?

A recent question on Usenet made me pause for thought: Why does new return a pointer rather than a reference?

Of course, one can use history as an excuse. Nevertheless, I still find it interesting to wonder whether it would be better for new to return a reference were it defined from scratch today.

The person who asked the question pointed out that new normally signals failure by throwing an exception, so, like a reference, the result of new cannot be null. Therefore, by returning a pointer, new implicitly offers an error-detection mechanism that it declines to use. If new were to return a reference instead, it would be clear that there is no need to check the return value for possible failures.

I started to compose a response about how pointers were easier to manage than references, when suddenly a thought occurred to me. Putting aside the new(nothrow) option, which does allow new to return a null pointer, there is still the common use of new to allocate an array.

In general, people use new to allocate arrays when they don't know in advance how many allocates the array should contain. In that case, of course, the type of the array isn't known during compilation--because the type of an array includes its size. So in that case, new cannot return a reference, because it's not possible to know the type to which the reference would refer.

So why not return a reference to the first element? Because the common use of new in such cases is to use the value returned as a way of accessing the elements of that array--in other words, to use it as an iterator.

Realizing that the new-array case really returned an iterator, I no longer felt that there was any reason for new to return a reference. The point is that pointers can serve as iterators and references can't--a fact that makes pointers a much better choice than references in this context.

Posted by Andrew Koenig at 11:28 AM  Permalink




 
INFO-LINK


Related Sites: DotNetJunkies, SD Expo, SqlJunkies