Wednesday 15 May 2013

c++ - How to replace delete and delete [] -



c++ - How to replace delete and delete [] -

i want replace delete , delete[] _delete ptr; need because delete method doesn't set ptr null. illustration i'm using code memory clean up:

#define _delete( ptr ) { delete ptr; ptr = null; } #define _deletea( ptr ) { delete [] ptr; ptr = null; } myclass *cls = new myclass(); int *value = new int value[100]; .... _delete(cls); _deletea(value);

but want utilize function like:

_delete cls; _delete value;

is possable?

or if not how replace with:

_delete cls; _delete[] value;

this isn't idea. macros not proper tool job. aside fact isn't possible, confusing maintaining code. there several superior alternatives.

if have c++11, should prefer utilize smart pointers such std::unique_ptr , std::shared_ptr whenever possible. matthiasb makes valid point should opt take advantage of standard library , utilize std::vector instead of dynamically allocated arrays.

otherwise, can take advantage of tools valgrind , llvm's addresssanitizer. it's available in clang , has been ported gcc 4.9. utilize it, specify -fsanitize=address @ command line.

if insist on textual replacement, manual search-and-replace in favorite ide might trick. wouldn't recommend though.

a give-and-take in is practice null pointer after deleting it? reveals practice indicative of possible design problems in program. example, jalf's answer:

setting pointers null after you've deleted pointed can't hurt, it's bit of band-aid on more fundamental problem: why using pointer in first place? can see 2 typical reasons:

you wanted allocated on heap. in case wrapping in raii object have been much safer , cleaner. end raii object's scope when no longer need object. that's how std::vector works, , solves problem of accidentally leaving pointers deallocated memory around. there no pointers. or perhaps wanted complex shared ownership semantics. pointer returned new might not same 1 delete called on. multiple objects may have used object simultaneously in meantime. in case, shared pointer or similar have been preferable.

my rule of thumb if leave pointers around in user code, you're doing wrong. pointer shouldn't there point garbage in first place. why isn't there object taking responsibility ensuring validity? why doesn't scope end when pointed-to object does?

c++

No comments:

Post a Comment