When should I use new operator?
Hello all!
I'm have some expirience in pure C++ programming
and I have basic knowlegde about dynamic memory allocation
For example if I want to create table wih X int elemtens I use
int *pint = new int[X]; // later - delete [] pint;
but in Qt there are a lot of dynamic objects, for example shoud I use new
operator for QList class
QList *myList = new QList; or
QString * myString = new QString;
or just
QList myList;
QString myString;
so my question is - when should I use new operator in Qt?
Re: When should I use new operator?
A general rule is to use the new operator with all objects that are derived from QObject with optional exclusion of those that you do not pass a parent (like often QSettings or QFile) or those that are shortlived (like QDialog that will have QDialog::exec() called on it). The second general rule is to allocate all objects that can be copied (ones that have a public copy constructor, such as QList, QColor, QFontMetrics, etc.) on the stack (without the new operator). Most objects in Qt can be copied, so most can be created on the stack.
Re: When should I use new operator?
You may want to read up on Pointers.
http://www.tek-tips.com/faqs.cfm?fid=2914
Using pointers in Qt is no different to using them in pure C++.
On a side note QList is a template Class so you need to specify what You want it to contain. For example the declaration for a list of doubles would look something like this:
Code:
QList<double> myList;