[CPP] Reference, new and delete
Reference
- A way to give a new name to an item
- look like normal variables
- act like pointers
The need for references
- Useful if we need to keep the same syntax(but avoiding making a copy)
- Useful as return values, to chain functions together(especially returning *this from member functions to return reference to current object)
- References are necessary for operator overloading(changing the meaning of operators)
warning
Similar problems with references as with pointerse.g. do not return a reference to a local variable
When the local variable vanishes (e.g. the function ends), the reference refers to something that doesn’t exist.
new and delete
new vs malloc
- new knows how big the object is: no call to sizeof() is needed (unlike malloc() )
- new creates an object ( and returns a pointer): allocates memory (probably in same way as malloc() )
- new knows how to create the object in memory: c++ objects can consists of more than the visible data members
- new calls the constructor (malloc() will not )
- new throws an exception(bad_alloc) if it fails: by default, unless you tell it not to.
What new really does?
When you call new, the compiler generates code to:- Call operator new (to allocate the memory)
- Create the object: including hidden data(e.g. vpointers)
- Calls the constructor code
delete
delete destroys an object- It cares about the object type
- Calls the destructor of the class it thinks the thing is (using pointer type) and then frees the memory
new[] and delete[]
- new and delete have a [] version for creating and destroying arrays
- Default constructor is called for the elements
- you must match together
- new and delete
- new [] and delete[]
- malloc() and free()
pointer problems
- The same kind of problems can occurs with new and delete as malloc() and free():
- memory leak(leaking memory-less available): not calling delete on all of the objects or arrays that you new
- dereferencing a pointer after you have freed/deleted the memory it points to
- Calling delete multiple times on same pointer
Remainder
- If you want to create objects in dynamic memory then you must go through new(not malloc() )
- You can use new on basic types(e.g. int): By default they are not initialized
评论
发表评论