What is the difference between the following- |
- A constructor is automatically called whenever an object is created.
- new is the C++ operator to dynamically create objects (new will call constructors)
- malloc is the C function to dynamically allocate memory (malloc will
not call constructors)
- A destructor is automatically called whenever an object is destroyed.
- delete is the C++ operator to destroy objects created with new (delete will call destructors)
- free is the C function to release dynamic memory allocated with malloc (free will
not call destructors)
And what are the general rules to take care of so that memory does not leak? |
Some general rules:
- Don't use malloc/free at all. They don't have any place in C++. They're for C.
- Don't use new/delete unless you absolutely have to (read: 99% of the time you do not have to).
- Use container classes like vector, map, set, deque, etc to handle dynamically sized arrays/containers. Let those classes worry about allocation/destruction.
- Use smart pointers like unique_ptr, shared_ptr, etc for individual allocations.
- RAII is your friend. If you are manually deleting objects or doing cleanup... you are probably doing something wrong.