about "delete" and "delete []"

Started by
34 comments, last by xiajia 11 years, 2 months ago
Why do you feel the need to call `new' at all? I rarely do it. Your members should be objects, not pointer to objects, unless you have a good reason ("I used to be a Java programmer and feel the need to write `new' all over the place" is not a good reason).

do you mean call ‘new’ at the constructor?This is just one case.Not always the case.

Advertisement

Why do you feel the need to call `new' at all? I rarely do it. Your members should be objects, not pointer to objects, unless you have a good reason ("I used to be a Java programmer and feel the need to write `new' all over the place" is not a good reason).

do you mean call ‘new’ at the constructor?This is just one case.Not always the case.



No, I mean what I said. I very rarely use `new' in my code. When I do, it's almost always in factory classes.
I'm not sure why you're objecting in this case. Heap allocating the reference count in a non-intrusive reference counting smart pointer is perfectly normal. Not that there aren't other issues to look at here (such as those already mentioned as well as exception safety).

I have yet to learn the knowledge of design patterns, I learned the factory pattern to do some more in-depth discussion.

I guess the objection is simply because with only the latest example code, it boils down to

class MyClass
{
public:
    MyClass() : ptr_(new something) {}
    ~MyClass() { delete ptr_; }
};

That on its own is usually not just pointless ("something" should just be a regular member), but also a time bomb just waiting for an instance being accidentally copied (assigning it or passing it to a standard container). So usually whenever you see this kind of pattern and it really is necessary, explicitly making it non-copyable or supplying assignment and copy constructor should become almost a reflex.

Since this is just example code, it most likely doesn't apply, but still, I've encountered production code where the author thought that setting the pointer to NULL in the destructor will somehow magically affect all the other objects that have a copy of that pointer.

f@dzhttp://festini.device-zero.de

use smart pointer or use reference counting can solve this problem.

This topic is closed to new replies.

Advertisement