one of the cpp files has a structure pointer created with "new" operator. Should that pointer be explicitly deleted? Or is the pointer automatically deleted?
C++ does not (normally) have automatic memory management. To free up the memory of that object you would use delete. When to use it is a different question.
EDIT: Also, the pointer will be deleted (or will be overwritten on the stack) when the function returns, but the object pointed at will stay in the heap until you delete it.
The use of the 'new' keyword will allocate memory on the heap, the same way 'malloc' does in C. To get that memory back when you're done using it, you have to do a 'delete' on the pointer returned from the 'new'.
This is easy when the life of some object does not extend outside the function where it was instantiated, but becomes more complicated when these objects are returned or added to collections...
As #Jared Updike notes, you have to do this by yourself. That's one reason why smart pointers such as those in Boost and C++0x are so widely used - they are lightweight classes that manage an underlying raw memory pointer, to avoid memory leaks when (not if) you forget to delete or delete[] raw pointers.
If you are new to C++ do yourself a favour and take a look at those (scoped_ptr, shared_ptr etc).
If you are looking for easier memory management, you may want to look at Shared Pointers . They are a convenient way to assure you that the memory will be freed if correclty used.
Related
I'm totally new to C++. I would like to ask about the following.
If a member variable is dynamically allocated in the constructor. Should it always be deleted in destructor? If so, then how is the variable's lifetime "elongated"? If not, how should memory leak be handled otherwise?
I couldn't find any source to address this issue explicitly.
Reasons to allocate a member dynamically are
The size of an array may be non-constant
The member could be very large, such that there is not enough memory on the stack
The member is polymorphic, as commented by MSalters
But, as Alf already pointed out in a comment, it is preferable to use a smart pointer. This has the advantage that you don't need to explicitly delete that member in the destructor, and in the case of a shared_ptr, you can elongate the liftime as needed, the smart pointer takes care of the destruction.
Should it always be deleted in destructor?
Not a necessity - you can free up the memory as soon as the work is done by some other function, if you are sure it won't be used any further. But, you must anyway call this destruction routine from destructor also to avoid memory leak. Ideally, you'd also need to provide another function for ReAllocate the memory.
In short, it all depends on your class and what are you implementing.
Let me take some post-modern approach and say "you don't have to worry about it anymore"
use unique_ptr if only the creating-object is incharge of that resource, use shared_ptr if many objects share that resource. use STL containers for all other possible uses.
use new and delete only if you're writing something extremely low-level or implementing a container from scratch. for all other cases, view dynamic memory allocation (via malloc and new) as deprecated.
If you allocate some space dynamically for example
struct node*py=new struct node;
struct node*tr=py;
delete py;
shouldn't the allocated memory still remain and not be freed since I do have another pointer pointing to the same address before the original pointer to the same is deleted?
No. That's simply not how memory allocation works in C++.
If you allocate memory with new, and then you call delete on it, it will get deleted. The memory manager has no facility for canceling or aborting a deletion once it's begun. C++ has a tendency of doing exactly what you ask it to do, so if you don't really want to free some memory, then don't call delete on it yet.
If you want reference counting, try using std::shared_ptr (or boost::shared_ptr, if you don't have the one in std yet).
no, the heap manager just does what it's told and frees the memory.
If you want to retain the memory based on how many references you have to the memory, then consider using reference-counted pointers such as C++11 shared_ptr (see, e.g., Dr Dobbs) or boost's smart pointers.
But you said it yourself - its only a pointer, therefore it doesnt know to what it points. it simply points to somewhere blindfolded.
No, in c/c++ the compiler/execution environment does not track refrences to memory, new and free mark memory as in use or not in use, and any refrence counting or other higher order garbage collection is left up to your program.
I'm writing a C++ destructor (I hope that's the right term; I'm new to C++) and I'm not positive on what exactly I need to garbage collect. Let's say I have 2 pointers as instance variables do I need to garbage collect them? What about if I have an object as an instance variable? Or a pointer to an object?
I'm just a little fuzzy on what exactly needs to be deleted and what is automatically cleaned up.
Thanks
General rule of thumb is... if you called new, call delete. If you called new[], call delete[]. If you're accessing these pointers outside of the class and effectively sharing them, you'll want to be careful about the "owning" object deleteing the shared objects while they're still in use. Garbage collection isn't quite the right term. You want to destroy the object and free its memory. This is what delete/delete[] does. new/new[] allocate memory and construct an object.
In C++, there is no garbage collector. You must "manually" handle it. That's not to say that it's all tedium. You'll probably get into using smart pointers to handle some of this logic for you. See this question for more information.
You must delete every pointer you allocate with new. It's that simple, and it's that complicated; you must not lose track of any pointer allocated by new until you have deleted it.
Also, you need to make sure that if you use new[] to allocate a pointer, you call delete[] to deallocate it.
It's not about what pointers you happen to have in a class instance. You need to know who owns them (the owner is the one responsible for deleting them). If your object owns those pointers, then it should delete them. If it doesn't own them, then it shouldn't.
This is also why experienced C++ programmers avoid naked pointers where possible. Smart pointers allow you to express ownership types semantically in the language. That way, you don't have to keep track of who owns what; you know who owns it by the type of smart pointer being used.
You must call delete on every space you created using new, delete[] on every area created using new[], and free on everything you got using malloc.
You should also close any sockets you opened, and clear up any other OS resources your class owns.
Note: this is not called garbage collection. Garbage collection is when this process happens automatically, as part of a library or language runtime, not when you do it explicitly.
You should start by learning about "Resource Acquisition is Initialization" (RAII) and smart pointers (shared_ptr and unique_ptr). This is the idiom you have to know in C++ if you come from other languages.
Usual practice says that whatever you allocated in your constructor must be deallocated in your destructor (see other answers to know how). Event better, try to use values as much as possible and new as less as possible.
C++ loves the stack, and stack allocation and deallocation are automatic and cheap (no new, no delete). Use references and const-references instead of pointers.
If you really need dynamic memory, try to use one of the smart pointers.
Any memory you allocate using new operator needs to be freed.
You allocate memory by doing:
int * p1 = new int[5];
p2 = new int;
and you delete it by doing:
delete[] p1
delete p2;
If you are playing with Classes, you need to do the same thing in constructors (allocate) and destructors (deallocate).
In an ideal world, nothing. There are smart pointers and containers for every pattern. Sometimes, you will have to write your own, or augment existing implementations, but much of what you need exists already.
For an array, start with std::array and std::vector. For objects, read up on smart pointers and shared pointers. As a generalization: if you need to call delete, delete[] or free, you have usually headed down the wrong path.
You need to garbage collect all pointers that you don't no longer need. Otherwise you would have the dangling pointer problem.
Today I was asked about smart pointers in C++, and I can't find anywhere useful information about it..
Please, can someone tell:
What is smart pointers?
When do you need it?
Do you have any example where smart pointers is actually useful?
Thank you!
Primarily, smart pointers help you to:
Avoid leaks when exceptions are thrown. When an exception is thrown, you don't want any objects that are allocated earlier in the try block to be leaked. By wrapping them in smart pointers, which will be destroyed when the try block is exited, those objects will get properly destroyed.
Manage lifetime by reference counting owners to objects (i.e., the last one to destroy its smart pointer referencing a particular object actually deallocates the object). This is especially helpful in loosely coupled scenarios where it is not clear at what time the object should be destroyed, because users of the object do not know about each other.
A good example of where smart pointers are useful:
A vector of pointers to objects. By
making it a vector of shared pointers,
for example, the objects will
automatically be deallocated when the
vector is destroyed and/or objects are
removed. This automates object lifetime management and helps the user of the container avoid memory leaks.
Excerpt from Boost Smart Pointers (smart_ptr) lib:
Smart pointers are objects which store
pointers to dynamically allocated
(heap) objects. They behave much like
built-in C++ pointers except that they
automatically delete the object
pointed to at the appropriate time.
Smart pointers are particularly useful
in the face of exceptions as they
ensure proper destruction of
dynamically allocated objects. They
can also be used to keep track of
dynamically allocated objects shared
by multiple owners.
Conceptually, smart pointers are seen
as owning the object pointed to, and
thus responsible for deletion of the
object when it is no longer needed.
Smart pointers handle their own memory management by keeping track of how many references point to the memory. Once there are 0 references, it deletes the memory for you. Makes memory management easier.
Smart pointer general refers to a class that behaves like a pointer. You can use the class to store a pointer to memory that you allocate, and access data through the pointer.
The advantage is that, when used inside functions and methods, the smart pointer can be made to automatically deallocate the memory once the variable goes out of scope. Otherwise, this is a prime opportunity for a memory leak when functions fail to free all allocated memory.
For an example, check out http://msdn.microsoft.com/en-us/library/txda4x5t(VS.80).aspx.
A smart pointer is an object that dynamically allocates memory for the thing that it points to, and when the smart pointer goes out of scope it automatically deallocates the memory for the thing that it points to. It's useful when you want something that's deallocated when it goes out of scope, but that's too big to put on the stack (or has other issues that prevent it from being able to be put on the stack).
A smart pointer essentially manages memory allocated on the heap with an object allocated on the stack.
Because objects allocated on the stack have a fixed lifetime (i.e. within the scope they are declared) deallocation of the heap memory is deterministic and guaranteed to happen.
Smart pointers are basically objects that perform functions similar to pointers
they are used to lessen the allocation and deallocation time. For C++ one common example would be of auto_ptr
I have a function that allocates memory using the new keyword.
That array gets returned from the function, but I need to somehow free it. Is it ever freed after the function returns, or is it up to the receiving code to free the array after it is done with it?
Should I just make this array a member variable, and free it in the class destructor?
If you allocate memory explicitly with new, you must free it explicitly with delete. Local variables will be freed upon return; classes like vector may do some allocation behind the scenes but they will clean that up for you.
In general, C++ largely lets you pick your memory management model. You can stick with locals and non-pointer class members and get scope-based allocation. You can play with pointers and malloc/free or new/delete (but never free() a new'd pointer and vice versa!). Or, you could grab Boost and get boost::shared_ptr for reference counting semantics.
Should I just make this array a member variable, and free it in the class deconstructor?
That's generally a very good idea, but why reinvent the wheel? Just use std::vector<T>.
It depends. You need to define who has got the ownership of such object.
You can allocate the array in your function, return it, and let the caller free it, or put a pointer to it in a class which will destroy the pointer in the destructor.
If the ownership for such object should be shared among many entities you should use something like a shared_ptr.
I'd also suggest to always use some kind of smart pointer to handle your raw pointers.
Take a look at boost::shared_array. It does what you need.
Either that, or use std::vector