Subhransu Sahoo wrote:
Hi All,
Can anyone explain me why the return type of new MyClass[10] is
MyClass*. I think that it should be MyClass (*ptr)[] or MyClass**. Is
it dependent on the compiler implementation of new[] ?
Since you need
Regards,
Sahoo
No, if the return type was pointer_to_pointer then new would only be
allocating one element. That would be bad news.
Consider:
MyClass p_array[10];
MyClass represents the element type involved. The pointer's type is
therefore absolutely critical.
p_array, which decays to a pointer, is actually "storing":
a) a const count of elements <- thats hidden from you
b) the type of all elements (by typing the pointer itself) <- thats the
key
c) the address of the first element
Thats how the program knows how_many_times to invoke the _appropriate_
ctor and d~tor starting from where. Which also explains why you can't
pass an array by value or reference (you would loose the count).
Alternatively:
int main()
{
MyClass* p_array = new MyClass[10];
// do stuff
delete [] p_array; // ???
}
Question ???: How does the program know how many d~tors to invoke at
delete []? How does the program know _which_ ctor and d~tor to invoke?
Imagine what would happen if p_array - a pointer(* p_array) - had
MyClass* and not MyClass as a type? Have you ever seen the d~tor for a
pointer? Do you see how critical type MyClass is?
Is this a lousy way of doing things? Yes. But its not worth breaking
old code. Should the language change the way an array works? It has -
you shouldn't be using an array - they are evil.
http://www.parashift.com/c++-faq-lite/containers.html
Use a std::vector instead.
std::vector< MyClass v(10);
Unlike arrays, i can pass a vector around by value or reference and its
dynamic.
void foo( std::vector< MyClass >& r_vector)
{
// do whatever
}
Why deal with dumb, buggy pointers anyways? Why hastle with primitive,
fixed-size, brain-dead arrays?