Auto Deleting New Operator - c++

I was reading through the wxWidgets tutorial: http://docs.wxwidgets.org/trunk/overview_helloworld.html
And I noticed that they use new without delete. How is this possible :S How can you use new on a class without deleting it :S It doesn't make any sense to me :l
Can someone explain what's going on?

At the end of a program's execution, all memory in the process' memory space is freed by the OS.
It is likely that the tutorial showed you a simple example that requires the instantiated objects live until the end of the program.
For example, creating the window for the program will live until the program exits. So it is not necessary to delete this since the OS will do it for you.
I am not saying this is good practice, I always suggest that you explicitly take care of freeing memory to get in good habits.
There are other options in c++, such as smart pointers, which handle deletion of objects when refcounts reach 0, but I don't think that is what is happening here.

Some class libraries have a rule which gives the ownership of pointers as children to a parent object.
In this case, when you new an object and pass it to an owner object, it is the task of the owner to delete the pointer.
For example, a widget object adds GUI controls in its children-list, when the owner is going to be deleted, its destructor delete the children.
Read the documentation of wxWidgets about avoiding memory leaks:
Child windows
When a wxWindow is destroyed, it automatically deletes all its
children. These children are all the objects that received the window
as the parent-argument in their constructors.
As a consequence, if you're creating a derived class that contains
child windows, you should use a pointer to the child windows instead
of the objects themself as members of the main window.

You CAN use New without Delete, but only if you want the lifetime of the object to last until the program exits. Generally, it IS considered bad form.

Yes, it's possible to use new without calling delete but in general it's bad form. However just because you call new without explicitly calling delete yourself does not mean it is not called. In regards to GUI frameworks many of them handle calling delete internally based on external events. For instance if you call new to create an object that represents a window the GUI framework may call delete when the OS destroys the window. It may not be obvious unless you are familiar with the framework or read the documentation for it.
There are also "smart pointers" which are objects that hold a pointer to a particular resource and release (delete) it when the smart pointer itself is destroyed. Boost and C++11 provide implementations of smart pointers (std::unique_ptr for instance) which are used quite often to manage the lifetime (and ownership) of objects created using new. This of course is a generalization of smart pointers as there are various implementations that use reference counting or other mechanisms to ensure that the resource is released only when it is no longer used.
There are many articles floating around the web concerning smart pointers, resource lifetime, resource ownership, etc. A quick Stackoverflow or Google Dance for "C++ smart pointers" will give you a vary large list of resources for further reading. Searching for the acronyms RAII and SBRM will also bring up a large list of resources.

This has got to do with the way the wxFrame class is implemented. The object will be deleted when the frame is closed.
Quoting the wxWidgets documentation:
The default close event handler for wxFrame destroys the frame using Destroy().
Typically you do need to delete objects you allocate with the new, but in this case someone else is doing it for you.

Related

Can I use QCoreApplication::instance() for Orphan QObjects?

For QObjects created on the heap with no parent, I found that destructor is not called. So, I starting using the core application instance as their parent to ensure that they are cleaned by garbage collector. Is this the right action, or what should I exactly to safely de-allocated these objects?
Here is an example of what I am doing:
// Use application instance as parent to avoid memory leak if object is not deleted
m_qObject = new DataHandler(QCoreApplication::instance());
Qt doesn't have an independent memory management, such as a garbage collector. The explicit parent-child relationship used is a classic ownership model that helps in the automatization of object life-cycles, it is deterministic (it will delete object on parent's destruction), and it is very natural with user interfaces.
If an object is created (in the heap) without a parent, it will generate a memory leak when the last reference to it is lost. Objects in the stack should not have a parent to prevent double-delete errors (check Qt documentation for further information)
If you set QApplication::instance as the parent of an object, you are basically telling it not to be destroyed until the application quits. If that's the case, then there is no such a great difference with other standard memory leaks, escept the object's destructor does something else than just releasing memory (such as closing OS-wide handles, saving files, etc).
There is a very interesting case I was curious about: what happened when the original parent (Q*Application::instance) was replaced at any given moment, as in this question?
The case is that the ownership of the object is transferred from the former Q*Application instance to the new one. It may become a problem if you rely on the existence of the object through the whole application life-span but several instances of Q*Application are allowed to be created and destroyed at any moment. One scenario would be a non-Qt application loading plug-ins or components built on Qt, in where you cannot control the creation/destruction order.
If that's the case, I'd suggest to find another way to destruct your object, such as having your own singleton inheriting from QObject that you can use as parent.

Memory leak when transferring custom data (Type*) with QStandardItem?

I have a QTreeView with associated QStandardItemModel and QStandardItem's that fill the model. Then i also have a slot function that connects to clicked(QModelIndex) on the model and does some stuff. While building the model i would like to pass in some custom data to the QStandardItem's so that the slot function can do something with it. I managed to get this working through the method described here.
However i'm concerned about there being a possible memory leak with this method and what to do about it. If it does leak, i cant delete it from the associated slot function since the view will still be there and the user may click the same item again (and then point to a NULL reference) and im not totally sure about possible ways to enclose the pointer with a smart pointer because of the relationship with the Q_DECLARE_METATYPE(Object*) macro and how data is set to QStandardItemto
So does this cause a memory leak without an associated delete here and if it does, what are the best ways to get around this?
If you declare a pointer as metatype, Qt will internally manage the pointer alone, so it's your responsibility to ensure that the object is deleted in due time (by deleting it manually and clearing references to it or assiging a parent to it and ensuring the parent is deleted. You can avoid memory leaks by using value-based metatype, e.g. Q_DECLARE_METATYPE(MyClass). However MyClass should have copy constructors so QObject will not do. You can also use shared pointers: Q_DECLARE_METATYPE(QSharedPointer<QObject*>). Qt will internally keep shared pointers and delete them when appropriate view items are removed, so the underlying object will be deleted if your code doesn't contain another shared pointers to it. Refer to QSharedPointer documentation to learn how to use it correctly.

Is there a safe way to use C++11 Smart Pointer and the Interface for Raw Pointer together?

I want to use C++11 Smart Pointers in new projects, and encounter a problem. Many current projects still use raw pointers as parameters in their interface and have no interface for smart pointers, e.g. QMainWindow::setCentralWidget.
To keep type consistent, I have to pass the stored pointer from get() like this segment:
QMainWindow win;
std::shared_ptr<QWidget> scrollArea{ std::make_shared<QScrollArea>() };
// QScrollArea is a derived class of QWidget.
win.setCentralWidget(scrollArea.get());
But I can't make sure whether other methods in Qt execute operator delete on the stored pointer of scrollArea.
Will it cause memory leak or other problems if some methods in Qt do that?
I've checked the latest C++ Standard CD and found nothing on that. Seems it's an undefined behavior.
If doing this is an undefined behavior and dangerous, is there a safe way to use smart pointer(s) with the interface for raw pointer(s)?
There's no such way in the general case. For each "legacy" interface you want to use, you must read its documentation to see how it interacts with ownership (which is what std smart pointers encapsulate). A single object can only be managed by one ownership scheme.
With Qt in particular, it's definitely not safe to mix smart pointers and Qt management. Qt's parent/child relationship between QObjects includes ownership semantics (children are deleted when their parent is), so you cannot safely mix this with any other ownership scheme (such as std smart pointers).
Note that the Qt docs you link to explicitly state that "QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time."
Unfortunately, if you are using an interface that uses raw pointers, you will need to consult the documentation to determine if the method does or does not take ownership of the provided pointer.
If the function takes ownership, then you must invoke .release() to transfer the ownership to the function. If the function does not take ownership, then you would pass the object with .get().
Will it cause memory leak or other problems if some methods in Qt do that?
It won't introduce a memory leak, since the memory is afterall released. However, since both QT and the shared_ptr would call delete on that memory, you would likely get some nice heap corruption (UB in general).
is there a safe way to use smart pointer(s) with the interface for raw pointer(s)?
Sure. Don't have unrelated entities manage the same memory. For that it is adavantegous to use unique_ptr instead of shared_ptr when possible. With unique_ptr you could call .release() to release the memory from the control of the smartpointer, thus giving you the ability to give control over to QT.
Of course you need check the documentation to see when you have to manage memory yourself and when QT will do it for you.
I don't think you should be doing any deleting with the QWidget.
http://qt-project.org/doc/qt-4.8/qmainwindow.html#setCentralWidget
Note: QMainWindow takes ownership of the widget pointer and deletes it
at the appropriate time.
If you have to use smart pointers, you can use a weak_ptr which won't own or destroy it.
If you are using an interface which takes raw pointers, you already have the problem that you must know who is responsible for the lifetime of those pointers.
Adding shared_ptr into the mix doesn't change this.
If the interface will possibly delete the object, then you cannot use std::shared_ptr safetly. std::shared_ptr must control the lifetime of its objects and there's no way around this (without adding another level of indirection)
You can however get some use out of std::unique_ptr. If an interface will not delete a pointer, you can safetly pass in ptr.get(). If an interface takes ownership of the lifetime of that object, pass in ptr.release() and you give up controlling the lifetime yourself.
All in, you can get some usefulness out of smart pointers even with a legacy codebase, but you've got to be a little careful.
But I can't make sure whether other methods in Qt execute operator delete on the stored pointer of scrollArea.
If the widget has a parent, then the QT's memory management will release that object. In that case you must not use a smart pointer, because your application will try to release it twice, and that is an undefined behaviour.

Will using shared_ptr for returning pointers from a method always save me from memory leaks?

I'm a c++ newbie, my code currently new's up on the heap in several places without calling delete. I know I need to do something about this.
My typical usage is where I new up a class instance in another classes member method then the method returns the pointer to the object.
If i change the return types from MyType* to std::tr1::shared_ptr will this fix my code to not leak memory?
Thanks a lot.
Edit:
Also likewise, I currently store new'ed up objects as MyType* as a value in a std:map. This map is a private member to a class instance. If I simply change this to std::tr1::shared_ptr will this clear up these when it's owner (class) falls out of scope?
Thanks again
It's a reasonable band-aid, sure.
A shared pointer is a reference-counted pointer. So as long as one or more shared_ptrs exist pointing to an object, that object will be kept alive. The problem occurs if you have circular references. Then the reference count will never reach 0, and the object(s) will never be deleted.
So shared_ptr * still* require you to understand what you're doing and think about object ownership, as you always have to do in C++. But it simplifies some otherwise complex scenarios, where determining ownership is hard.
But the real fix to your problem is to:
minimize how much you allocate with new. Can the object instead be stored on the stack? Can the object be rewritten as a RAII class, so that a small wrapper object is allocated on the stack (or elsewhere with automatic storage duration), and which, through its constructors and destructors, manages a heap-allocated memory resource? Then, as long as that object exists, its allocated memory will be preserved, and once it is destroyed, it will delete its allocated memory.
when you allocate objects with new, put them in one of the smart pointer classes. shared_ptr is popular because it is the one that comes closest to looking like a garbage collector, but it isn't, and if you treat it as one and use it as an excuse to not think about memory management, then it won't work. Understand all the smart pointer classes (scoped_ptr and auto_ptr in C++03, or unique_ptr replacing both in C++11, shared_ptr and weak_ptr), and use the one that best fits your scenario.
think about ownership. Any time you allocate memory, you need to determine an owner, whose lifetime will control the lifetime of the memory allocation. Think about how long a lifetime your allocation needs, and have another object (whose lifetime is automatically managed, probably because it is on the stack) delete your memory when its destructor is called.
There's no quick and easy fix. The way to handle memory management in C++ is to avoid memory management. Delegate it out to your objects. If you're calling delete in your own code, you're doing it wrong. Often, you don't even need new, but if you do, assign ownership to a smart pointer immediately, and let that call delete for you.
As a rule of thumb, unless you're a library writer, you shouldn't write either new or delete. You should virtually never use raw pointers, and only when it is absolutely necessary, use smart pointers. Let your classes do the heavy lifting. Don't be afraid to put them on the stack, pass them by value, and let them handle their resources internally.
If you are new to C++ there are a few points with pointer management you need to understand and accept, regardless of whether you're using shared_ptr or not.
It is more than likely in your use of C++ you will need to use new and assign its return pointer to a class pointer that you have declared. I believe it is advisable to take the time to understand what is going on there, even if you write a small test program and watch the constructor execute in the debugger.
If you use classes like std::string, its constructors and destructor will do string pointer management for you, but I believe it is a good idea to understand what is going on behind the scenes in that class, if nothing more than reading the documentation.
As another example, you cannot use some classes, without a lot of detailed reading of the API, or you'll get problems. I once worked at company that used a commercial class package years ago. Someone had written a multi-threaded program using this package's thread pool class.
The documentation clearly said you can't just exit with outstanding threads. Yet I saw where the author of the program did not bother to synch up and shutdown all threads on exit, and wound up throwing exceptions, when their program exited. And this was on a commercial financial product.
My suggestion is don't look to get saved from performing pointer management. There are std classes like string that can reduce your headaches, but nothing will prevent problems other than your own diligence and testing.
As long as you understand how tr1 shared pointers work, yes.
Look at Boost C++ shared_ptr<> also - it might be more what you want.

Unmanaged C++ Garbage Collection help

I'm a .net programmer, without much experience with unmanaged code. I've been adding modifications and additions to an unmanaged project, and everything is functioning just fine. Can you give me some pointers as to what kind of code/objects I need to be concerned about in regard to garbage collection?
TIA
None. C++ doesn't have a garbage collector.
On C++ when you allocate memory manually using the new operator, its your job to release this memory later (when its no longer needed) using the delete operator.
What is the difference between new/delete and malloc/free?
If you have everything on the stack, or construct elements into containers such as vector then you won't have to worry about memory.
It is however likely you use at least some form of memory allocation (new/malloc/createobject/globalalloc/sysstring/...)
MSVC (COM) ATL provides managing 'RAII' types to help manage lifetime of objects
CComPtr<> will manage scope
CComQIPtr<> will also manage scope, but will also change to the specified type on assignment.
C++ has std::auto_ptr<> which is a bit old and is heading for deprecated
boost/tr1 has a bunch of scoped/shared types for managing ptr & arrays - usage depends on if you use new or new[] so that it can call the right delete or delete[]
You tagged this COM. If so, you are responsible for calling AddRef() and Release() as appropriate for any COM objects you use. They control the reference-counting features in COM, and are not related to the .NET garbage collector.
For your unmanaged objects, you are responsible for calling delete when you are done with them.
karlphillip give you good advice.
Moreover I want to add, that when you are using objects, best places to delete them is destructor of the class.
you must be careful, because when you delete something twice, your program will blow up.
There is a useful trick to detect whether object was just deleted.
after deleting them, you can set pointer to null
delete foo;
foo=null;
next time you can check whether it is equal to null, and in otherwise delete them. And the best thing... even if you will try delete null pointer, nothing will happens! :)
Figure out if the code is using smart pointers (it probably is), the smart pointers should destroy objects themselves when they go out of scope.