help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: ISO C++ forbids initialization in array new


From: Dyreatnews
Subject: Re: ISO C++ forbids initialization in array new
Date: Wed, 14 May 2008 10:39:02 +0200
User-agent: Gnus/5.110006 (No Gnus v0.6) Emacs/22.1 (usg-unix-v)

Florian.Hudelist@googlemail.com writes:

> Hi,
> the system in my uni has finally been upgraded and now I am having
> some problems to compile my code.
> I want to initialize an array of an object but this is not allowed
> anymore. I found some discussions about this issue but no solution how
> to rewrite it. Simplest case when this problem happens:
>
> **************************************************************
> class array
> {
> private:
> public:
>       int s;
>       array(int i)  {s = i;}
> };
>
>
> int main()
> {
>       array *test;
>       test=new array[5](123);
> }
> ***************************************************************
>
> Compiling this code gives following error message:
>
> $ g++ test.cpp
> test.cpp: In function âint main()â:
> test.cpp:22: error: ISO C++ forbids initialization in array new
>
>
> How do I have to write the code to get the same result? I don't want
> to add an extra function to initialise my objects.

As the error message says; you cannot do this in std C++. I had a quick
look at the man/info pages for g++, but I could not see any option that
obviously would allow this behavior. That doesn't mean that it does not
exist - someone more knowledgeable about gcc might know.

The modern way would be to use std::vector which has a constructor that
accomplishes this. Using a vector would also make the code more robust
(less chance of memory leaks and exception safety issues).

I assume that the real example there is a good reason
to allocate the array on the heap, because in your snippet it might as
well have been allocated on the stack as you know the size of the array
at compile time...

-- 

Dyre Tjeldvoll


reply via email to

[Prev in Thread] Current Thread [Next in Thread]