John Harrison wrote:
> "Dario (drinking coï¬?ee in the oï¬fceâ?¦)" <> wrote in
> message news:c8i6nt$ahr$...
>
>> cppaddict wrote:
>>
>>> I am deleting some objects created by new in my class destructor, and
>>> it is causing my application to error at runtime. The code below
>>> compiles ok, and also runs fine if I remove the body of the
>>> destructor. So I think I am somehow using delete incorrectly, but I'm
>>> not sure exaclty what I'm doing wrong.
>>
>> A question: Why you "delete" something that you do not "new" ?
>>
>> In addPoint you add:
>> *( new Point(x,y) )
>> and not:
>> new Point(x,y)
>> so you cannot delete it.
>>
>> Probably you can rewrite your addPoint as:
>>
>> void Char::addPoint(int x, int y) {
>> Point * p = new Point(x,y);
>> _pixelPoints.push_back(*p));
>> delete p;
>> }
>
> That works but why?? Needless use of new, inefficient and error prone.
>
> _pixelPoints.push_back(Point(x,y));
Good point.
> What's so hard about the above that newbies fail to use it?
The explanation (at least for me) is the fact that I'm used
(since many years) to write in Java, where the only way to create
a new Object is via the "new" operator.
So (at least for me) the natural way is always
new Point(x, y)
But definitively in C++ the example mu be written as you said.
- Dario
|