Larry Brasfield wrote:[color=blue]
> "Berk Birand" <graffiti@yahoo.com> wrote in message
> news:1108357762.05636e8fef4de605858860b6ab18c07c@t eranews...[color=green]
> > Larry Brasfield wrote:[color=darkred]
> >> "Berk Birand" <graffiti@yahoo.com> wrote in message
> >> news:1108355721.1538885266d9be3798d4ce31daa7e0a7@t eranews...
> >> [snip]
> >>
> >>
> >>
> >> The above code uses the Product assignment operator
> >> to give an initial value to what malloc() has returned.
> >> This is incorrect. Assignment should only be done to
> >> already constructed objects. Using it on raw memory
> >> is likely to lead to the kinds of problems you mention
> >> in the subject line.
> >>
> >> If you insist on using malloc() rather than array new,
> >> then you need to use placement new to get the Product
> >> ctor to be executed on each block of raw memory that
> >> is to become a Product object. Then you can assign
> >> to it. Alternatively, you can use placement new and
> >> the Product copy ctor, if it has one.
> >>[/color]
> >
> > Hmm, this is awfully interesting. The professor hadn't mentioned[/color][/color]
this problem. The problem with new is that I need dynamic[color=blue][color=green]
> > allocation. The size of the array is not known beforehand, and as[/color][/color]
far as I know, new doesn't accept variables.[color=blue]
>
> Array new does.
> If 'SomeType' is a type name, (such as float, or 'Product' where
> you defined "class Product { ... }" somewhere), then you can
> get an array of SomeType objects by writing:
> SomeType * gobOfObjects = new SomeType[howMany];
> where 'howMany' names an integer with a positive value.
> Just remember to dispose of it via
> delete [] gobOfObjects;
> or an equivalent on the same pointer value.
>[color=green]
> > So, in the light of this new idea, what am I supposed to do??[/color]
>
> Having not seen your assignment, I'm not sure. But if your
> professor, when shown my post, does not agree with my
> criticism of the quoted code, then you should double check
> everything he/she says with a more reliable reference.
>
> I would be remiss not to mention that using std::vector<Product>
> would be a better solution than rolling your own array memory
> management, as your posted code apparently represents. If
> you were to look at the code for std::vector, you would see
> use of placement new as I mentioned.
>
> --
> --Larry Brasfield
> email:
donotspam_larry_brasfield@hotmail.com
> Above views may belong only to me.[/color]