Page 1 of 2 12 LastLast
Results 1 to 20 of 26

Thread: Basic question on new and delete

  1. #1
    Join Date
    Jan 2006
    Posts
    73
    Thanks
    16
    Thanked 3 Times in 3 Posts
    Qt products
    Qt4
    Platforms
    Windows

    Default Basic question on new and delete

    Hi,

    Quite a basic question concerning dynamic memory allocation.
    int main()
    {
    int* p = new int();
    return 0;
    }
    I am assuming that the above program is harmless to the computer. Is that right? Does C++ guarantee that on program termination, the memory pointed to by P is freed? Is there a good reason why I should still insert an "delete p';"? Is the answer the same for every operating system?
    Tanks and congratulations on the new qt forum.
    JCR

  2. #2
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,364
    Thanks
    3
    Thanked 5,012 Times in 4,791 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: Basic question on new and delete

    Quote Originally Posted by jcr
    I am assuming that the above program is harmless to the computer. Is that right? Does C++ guarantee that on program termination, the memory pointed to by P is freed? Is there a good reason why I should still insert an "delete p';"? Is the answer the same for every operating system?
    It is said to be OS dependent. For example on Linux the memory is freed for sure, but on Windows it is said to make a memory leak.

    Why should you insert a delete statement? For three reasons. First has already been mentioned -- a memory leak after the process ends. Second one is about elegance. Third is that one day you may want to reuse the code as part of some bigger framework and if you don't notice that missing delete (which is very likely to happen), you'll end up with a memory leaking process.

  3. #3
    Join Date
    Jan 2006
    Location
    Athens - Greece
    Posts
    219
    Thanks
    3
    Thanked 1 Time in 1 Post
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by wysota
    ...you may want to reuse the code as part of some bigger framework and if you don't notice that missing delete (which is very likely to happen), you'll end up with a memory leaking process.
    Think that you mght have an application that runs for several hours and that the memory is allocated meny times without freeing it, eventually your memory resources will run out and your app will remind you a very popular OS back in '95

  4. #4
    Join Date
    Jan 2006
    Location
    Germany
    Posts
    85
    Thanks
    1
    Thanked 2 Times in 2 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Re: Basic question on new and delete

    Another good reason for delete is that you may have, at another place, a memory leak. If you use a memory debugger to find these you will get much less warnings this way.

  5. #5
    Join Date
    Jan 2006
    Location
    Winnipeg, MB. Canada
    Posts
    17
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Or simply create all your objects as value types (ala RAII) and just let them die of natural causes when they're out of scope. After all, pointers are SO yesterday

  6. #6
    Join Date
    Jan 2006
    Location
    Athens - Greece
    Posts
    219
    Thanks
    3
    Thanked 1 Time in 1 Post
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by rh
    After all, pointers are SO yesterday
    I'm sooo with you. If you can avoid them you save yourself a lot of troubles

  7. #7
    Join Date
    Jan 2006
    Location
    Germany
    Posts
    85
    Thanks
    1
    Thanked 2 Times in 2 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Re: Basic question on new and delete

    Quote Originally Posted by rh
    Or simply create all your objects as value types (ala RAII) and just let them die of natural causes when they're out of scope. After all, pointers are SO yesterday
    That's a very bad idea: In another thread somebody did that:
    Qt Code:
    1. for(int i = 0; i < 5; ++i)
    2. {
    3. QThreadDerivedClass t;
    4. t.start();
    5. }
    To copy to clipboard, switch view to plain text mode 
    Just after starting the thread the instance will be destructed because it went out of scope. You need pointers to avoid some very ugly code. Maybe use them through something like boost::shared_ptr with automatic reference counting, it's even exception safe.

  8. #8
    Join Date
    Jan 2006
    Location
    Athens - Greece
    Posts
    219
    Thanks
    3
    Thanked 1 Time in 1 Post
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by Codepoet
    ...because it went out of scope...
    This was an implementation bug What would you prefer in the following situation?
    Qt Code:
    1. MyModalDialog modalDlg;
    2. modalDlg.exec()
    3. if(modalDialog.getSomething()==true){
    4. //do something;
    5. }
    To copy to clipboard, switch view to plain text mode 
    or
    Qt Code:
    1. MyModalDialog *modalDlg = new MyModalDialog;
    2. modalDlg->exec()
    3. if(modalDialog->getSomething()==true){
    4. //do something
    5. }
    6. delete modalDlg;
    To copy to clipboard, switch view to plain text mode 
    Then after code being added by many others...
    Qt Code:
    1. MyModalDialog *modalDlg = new MyModalDialog;
    2. modalDlg->exec()
    3. if(modalDialog->getSomething()==true){
    4. //do something
    5. }else{
    6. return; //Ouch
    7. }
    8. // Lot's of code that might also return somewhere
    9. delete modalDlg;
    To copy to clipboard, switch view to plain text mode 

    I'm not saying don't use pointers, but why not avoid them whem they are not needed?

  9. #9
    Join Date
    Jan 2006
    Location
    Germany
    Posts
    85
    Thanks
    1
    Thanked 2 Times in 2 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Re: Basic question on new and delete

    @yop: I cited not you but rh
    Yes one can (should?) avoid them if possible: Your example perfectly demonstrates it. It gets even worse when you work with exceptions.
    I never meant not using instances on the stack, that's most of the time ok but not always.

  10. #10
    Join Date
    Jan 2006
    Location
    Winnipeg, MB. Canada
    Posts
    17
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    The only real restriction to RAII-style initialized variables that i've encountered is, to state the obvious, that its type must be known at compile-time. Anything with runtime attributes (such as factory classes, etc.) still require pointers.

    My biggest qualm on using pointers? That damn "->" operator! C++ is *supposed* to be a language of type reduction, yet the arrow operator is 3x the keystrokes (don't forget the shift) as other dot-notated languages.

    If this makes me shallow (also i like ladies with big boobies), then so be it but in my opinion, RAII initialized variables are not only easier on the carpal tunnel, but are inherently safer (like GC without the overhead) and should be used whenever possible.

    I realize this is drifting slightly from the original post. If everyone is happy with me having the last word i'm good with that

  11. #11
    Join Date
    Jan 2006
    Location
    Lincoln, NE USA
    Posts
    177
    Thanks
    3
    Thanked 7 Times in 6 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by jcr
    Hi,

    Quite a basic question concerning dynamic memory allocation.
    int main()
    {
    int* p = new int();
    return 0;
    }
    I am assuming that the above program is harmless to the computer. Is that right? Does C++ guarantee that on program termination, the memory pointed to by P is freed? Is there a good reason why I should still insert an "delete p';"? Is the answer the same for every operating system?
    Tanks and congratulations on the new qt forum.
    JCR
    As I understand it C++ does NOT guarantee that the memory is freed. That is your job. And, I read somewhere that delete[] is the prefered form of that command, even if your pointer isn't an array.

    That's one of the beneies of using QT. If your class objects inherit from QObject or QWidget then QT's automatic garbage collection takes over, much as Java does. If your class objects don't inherit from those two QT objects then it's YOUR responsibility to make sure they get deleted before they lose scope.

  12. #12
    Join Date
    Jan 2006
    Location
    Germany
    Posts
    85
    Thanks
    1
    Thanked 2 Times in 2 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Re: Basic question on new and delete

    It is an error to use delete[] on a pointer allocated with new and vice versa. Everything else may work on some implementations on some not...

    Qt garbage collection works in principle like you described: But it suffices not to derive from QObject. QObject derived classes are guaranteed to be deleted when their parent is deleted. So when they have none it is still your responsibility to do it.


    @rh: Maybe switch to Dvorak? Helps not with "->" but everything else is great And I type much more other letters then these two... Maybe try something with autocompletion?
    Ah - you should use macros to avoid the curly braces - that would be wrist friendly

    And RAII-style should be used for pointers too - that's one of it's main applications when you program exception safe.

  13. #13
    Join Date
    Jan 2006
    Location
    Mountain View, CA
    Posts
    279
    Thanked 42 Times in 37 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by GreyGeek
    As I understand it C++ does NOT guarantee that the memory is freed. That is your job. And, I read somewhere that delete[] is the prefered form of that command, even if your pointer isn't an array.

    That's one of the beneies of using QT. If your class objects inherit from QObject or QWidget then QT's automatic garbage collection takes over, much as Java does. If your class objects don't inherit from those two QT objects then it's YOUR responsibility to make sure they get deleted before they lose scope.

    This is incorrect, the memory is always released back to the operating system at program termination. However, this is still technically a memory leak and it is good practice to use 'delete p' on your pointer.

    delete[] p should only used on pointers that were assigned to arrays created with new type[], e.g:

    Qt Code:
    1. int* p = new int; // delete with 'delete p;'
    2. int* a = new int[5]; // delete with 'delete[] a;'
    To copy to clipboard, switch view to plain text mode 

  14. #14
    Join Date
    Jan 2006
    Location
    Lincoln, NE USA
    Posts
    177
    Thanks
    3
    Thanked 7 Times in 6 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by Chicken Blood Machine
    This is incorrect, the memory is always released back to the operating system at program termination. However, this is still technically a memory leak and it is good practice to use 'delete p' on your pointer.
    I thought that the definition of a memory leak was a situation in which the memory was NOT returned to the OS at program termination. Successive leaks can "eat up" the heap until there is none left. How could memory be returned back to the OS and that memory still be a 'leak'? If the OS has it can't it re-use it?

    delete[] p should only used on pointers that were assigned to arrays created with new type[], e.g:

    Qt Code:
    1. int* p = new int; // delete with 'delete p;'
    2. int* a = new int[5]; // delete with 'delete[] a;'
    To copy to clipboard, switch view to plain text mode 
    I've read that too. But, IIRC, Tom Swan's book said that using "delete[] p" will 'guarantee' that p is deleted regardless of if it was array or not. I haven't tried in my app because my app doesn't use pointers, but the code example in Tom Swan's book didn't bomb.
    ???

    What would happen if one used "delete[]" on a pointer that wasn't an array?

  15. #15
    Join Date
    Jan 2006
    Location
    Mountain View, CA
    Posts
    279
    Thanked 42 Times in 37 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by GreyGeek
    I thought that the definition of a memory leak was a situation in which the memory was NOT returned to the OS at program termination. Successive leaks can "eat up" the heap until there is none left. How could memory be returned back to the OS and that memory still be a 'leak'? If the OS has it can't it re-use it?
    Consider a program that continuously calls 'new' in a loop without calling delete. This program is 'leaking' memory for every iteration of the loop and will eventually exhaust the physical memory in the system. The fact that this memory will be released when the program terminates is irrelevant here, because the program leaks more and more memory as it runs.

    Conversely, it is usually considered 'safe' to leak memory for variables that exist for the lifetime of the program, since that memory use is a constant and does not grow with respect to time as the program runs.

    I've read that too. But, IIRC, Tom Swan's book said that using "delete[] p" will 'guarantee' that p is deleted regardless of if it was array or not. I haven't tried in my app because my app doesn't use pointers, but the code example in Tom Swan's book didn't bomb.
    ???

    What would happen if one used "delete[]" on a pointer that wasn't an array?
    It would probably fine, but Stroustroup may not like it! Also, to a casual reader of the code, he may mistakenly think that the variable pointed to an array of memory. Using the correct variant of delete, makes the nature of the original allocation clearer.

  16. #16
    Join Date
    Jan 2006
    Location
    Lincoln, NE USA
    Posts
    177
    Thanks
    3
    Thanked 7 Times in 6 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Consider a program that continuously calls 'new' in a loop without calling delete. This program is 'leaking' memory for every iteration of the loop and will eventually exhaust the physical memory in the system. The fact that this memory will be released when the program terminates is irrelevant here, because the program leaks more and more memory as it runs.
    Ok, I see where you are coming from. While the program is running it is constantly leaking memory and will run out, probably crashing the program, if nothing else.

    But, after the program quites aren't the leaks still leaks... i.e., hasn't the memory been lost to the system until a reboot?

    And, doesn't QOBJECT take care of heap space that wasn't returned to memory when a) the object based on QOBJECT loses scope or b) the program quites? (Doesn't a=b?) Otherwise, if quiting the program recovers all leaked memory then the only purpose for QOBJECT is to prevent memory leaks (do garbage collection?) WHILE the program is running. Yet, I've seen several examples of programs that show a heap's size being reduced each time an app is run and then quites, so the the memory isn't returning to the heap (OS?) when the program quits.
    Last edited by GreyGeek; 30th January 2006 at 22:11.

  17. #17
    Join Date
    Jan 2006
    Location
    Mountain View, CA
    Posts
    279
    Thanked 42 Times in 37 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by GreyGeek
    Ok, I see where you are coming from. While the program is running it is constantly leaking memory and will run out, probably crashing the program, if nothing else.

    But, after the program quites aren't the leaks still leaks... i.e., hasn't the memory been lost to the system until a reboot?
    I don't believe this ever to be the case, but maybe there is a (faulty) OS that proves me wrong!

    And, doesn't QOBJECT take care of heap space that wasn't returned to memory when a) the object based on QOBJECT loses scope or b) the program quites? (Doesn't a=b?) Otherwise, if quiting the program recovers all leaked memory then the only purpose for QOBJECT is to prevent memory leaks (do garbage collection?) WHILE the program is running. Yet, I've seen several examples of programs that show a heap's size being reduced each time an app is run and then quites, so the the memory isn't returning to the heap (OS?) when the program quits.
    QObject is not a garbage collector and does nothing really spectacular. All it does is delete all of it's children when it is deleted nothing more (the children will recursively delete their children, etc). This is a simple parent-child pattern and is present in many GUI toolkits, even X-Motif! Don't forget, you still have to delete the topmost parent QObject for this to work. (A toplevel QObject always has a null parent)

    When a variable goes out of scope in C++, it is destroyed. Always. This is a guarantee of the C++ runtime and nothing else. The use of Qt/QObject is irelevant. This applies to all types of variables even pointers. However, when a pointer goes out of scope, the object pointed to is not destroyed. You have to take care of this with delete. There are alternative methods you can use to avoid this like std::auto_ptr and boost smart pointers, but at the fundamental level, you must deallocate the memory yourself.

    Where QObject really helps out is when you create a GUI. A toplevel window, say derived from QMainWindow, may contain a myriad of other subwidgets within itself (Consider a complex gui that you have created in Designer). When you intsantiate your main window widget, you may do it like this:

    Qt Code:
    1. MyMainWindow* mw = new MyMainWindow(0);// note null parent
    To copy to clipboard, switch view to plain text mode 

    Within the MyMainWindow constructor, there will be code that creates and arranges many child widgets of the main window.


    When you delete the mainwindow, you would do so like this
    Qt Code:
    1. delete mw;
    To copy to clipboard, switch view to plain text mode 

    You don't worry about deleting all the pushbuttons, listboxes, labels etc that are within your main window. Why? because QObject takes care of it with its parent-child model.

    To finish, consider the following example:
    Qt Code:
    1. MyMainWindow::doSomethingSlot()
    2. {
    3. // Create a dialog and show it
    4. MyDialog* dlg = new MyDialog(this); // parented to this mainwindow
    5. ...
    6. ...
    7. dlg->exec();// display the dialog
    8. }
    To copy to clipboard, switch view to plain text mode 

    This code leaks memory - badly. Why? You may ask. "I have parented my dialog to my main window, shouldn't it be cleaned up when the main window is destroyed?". Yes, but when will the window be destroyed? Probably somewhere just before your app terminates. How many times may doSomethingSlot() be called before this happens? Every time it is called an instance of MyDialog is created that floats off into the ether after it is no longer required.

    The preferred approach here would be to delete the pointer at the end of the function or to create the dialog on the stack instead of calling 'new'.

    [Incidentally, QObject::deleteLater() is often a better alternative to a straightforward 'delete' on a QObject, but that's another story!]
    Last edited by Chicken Blood Machine; 30th January 2006 at 23:14.

  18. #18
    Join Date
    Jan 2006
    Location
    Lincoln, NE USA
    Posts
    177
    Thanks
    3
    Thanked 7 Times in 6 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by Chicken Blood Machine
    ...snip...
    Where QObject really helps out is when you create a GUI. A toplevel window, say derived from QMainWindow, may contain a myriad of other subwidgets within itself (Consider a complex gui that you have created in Designer). When you intsantiate your main window widget, you may do it like this:

    Qt Code:
    1. MyMainWindow* mw = new MyMainWindow(0);// note null parent
    To copy to clipboard, switch view to plain text mode 

    Within the MyMainWindow constructor, there will be code that creates and arranges many child widgets of the main window.


    When you delete the mainwindow, you would do so like this
    Qt Code:
    1. delete mw;
    To copy to clipboard, switch view to plain text mode 

    You don't worry about deleting all the pushbuttons, listboxes, labels etc that are within your main window. Why? because QObject takes care of it with its parent-child model.
    Well, here is the main function, from my main.cpp, from my Homestead application:
    Qt Code:
    1. int main( int argc, char * argv[] ) {
    2. QString strRejected = "";
    3. QApplication app(argc, argv);
    4. app.setQuitOnLastWindowClosed(false);
    5. dlgLogin dlg;
    6. if( dlg.exec() == QDialog::Accepted ){
    7. QSqlDatabase hapdb = QSqlDatabase::addDatabase(DBDRIVER);
    8. hapdb.setHostName(DBHOST);
    9. hapdb.setDatabaseName(DBNAME);
    10. hapdb.setUserName(dlg.dui.leUserName->text());
    11. hapdb.setPassword(dlg.dui.leUserPassword->text());
    12. if ( hapdb.open() ) {
    13. homestead ht;
    14. ht.RevID = dlg.dui.leUserName->text();
    15. ht.show();
    16. app.setQuitOnLastWindowClosed(true);
    17. return app.exec();
    18. } else {
    19. strRejected = QString("The Login was rejected because: %1").arg(hapdb.lastError().text()).toLatin1();
    20. QMessageBox::information(0,"Login Rejected!",strRejected,
    21. QMessageBox::Ok,QMessageBox::NoButton,QMessageBox::NoButton);
    22. return 1;
    23. }
    24. } else {
    25. strRejected = QString("User Canceled the login!").toLatin1();
    26. QMessageBox::information(0,"Login Rejected!",strRejected,
    27. QMessageBox::Ok,QMessageBox::NoButton,QMessageBox::NoButton);
    28. return 2;
    29. }
    30. }
    To copy to clipboard, switch view to plain text mode 
    As I understand your comments, since "dlg" is called only once, and that call is in this function, its memory will be recovered when main goes out of scope (i.e., the app closes). And, hapdb is also instantiated only once so its memory, too, will be reclaimed when the app closes. The ht object, where Homestead really operates, is also instantiated only once and like the others, the memory it uses is returned to the OS when the app closes. So, I don't need as the last three lines of main():
    Qt Code:
    1. delete ht;
    2. delete hapdb;
    3. delete dlg;
    To copy to clipboard, switch view to plain text mode 
    because none of these objects leak memory, even though dlg has a parent:
    Qt Code:
    1. class dlgLogin : public QDialog
    2. {
    3. Q_OBJECT
    4. public:
    5. Ui::dlgLoginUi dui;
    6. dlgLogin()
    7. {
    8. dui.setupUi(this);
    9. dui.leUserName->setText("your revid");
    10. dui.leUserPassword->setText("");
    11. dui.leUserName->setFocus();
    12. dui.leUserName->selectAll();
    13. }
    14. };
    To copy to clipboard, switch view to plain text mode 
    but homestead does not...
    Qt Code:
    1. class homestead : public QMainWindow
    2. {
    3. Q_OBJECT
    4. public:
    5. homestead(QWidget *parent = 0);
    6. ...
    To copy to clipboard, switch view to plain text mode 

    Right?

  19. #19
    Join Date
    Jan 2006
    Location
    Mountain View, CA
    Posts
    279
    Thanked 42 Times in 37 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by GreyGeek
    Well, here is the main function, from my main.cpp, from my Homestead application:
    Qt Code:
    1. int main( int argc, char * argv[] ) {
    2. QString strRejected = "";
    3. QApplication app(argc, argv);
    4. app.setQuitOnLastWindowClosed(false);
    5. dlgLogin dlg;
    6. if( dlg.exec() == QDialog::Accepted ){
    7. QSqlDatabase hapdb = QSqlDatabase::addDatabase(DBDRIVER);
    8. hapdb.setHostName(DBHOST);
    9. hapdb.setDatabaseName(DBNAME);
    10. hapdb.setUserName(dlg.dui.leUserName->text());
    11. hapdb.setPassword(dlg.dui.leUserPassword->text());
    12. if ( hapdb.open() ) {
    13. homestead ht;
    14. ht.RevID = dlg.dui.leUserName->text();
    15. ht.show();
    16. app.setQuitOnLastWindowClosed(true);
    17. return app.exec();
    18. } else {
    19. strRejected = QString("The Login was rejected because: %1").arg(hapdb.lastError().text()).toLatin1();
    20. QMessageBox::information(0,"Login Rejected!",strRejected,
    21. QMessageBox::Ok,QMessageBox::NoButton,QMessageBox::NoButton);
    22. return 1;
    23. }
    24. } else {
    25. strRejected = QString("User Canceled the login!").toLatin1();
    26. QMessageBox::information(0,"Login Rejected!",strRejected,
    27. QMessageBox::Ok,QMessageBox::NoButton,QMessageBox::NoButton);
    28. return 2;
    29. }
    30. }
    To copy to clipboard, switch view to plain text mode 
    As I understand your comments, since "dlg" is called only once, and that call is in this function, its memory will be recovered when main goes out of scope (i.e., the app closes). And, hapdb is also instantiated only once so its memory, too, will be reclaimed when the app closes. The ht object, where Homestead really operates, is also instantiated only once and like the others, the memory it uses is returned to the OS when the app closes. So, I don't need as the last three lines of main():
    Qt Code:
    1. delete ht;
    2. delete hapdb;
    3. delete dlg;
    To copy to clipboard, switch view to plain text mode 
    That would not even compile. None of the variables you mentioned are pointer variables, so how could you ever call delete on them? Your code (above) as listed will not leak any memory, because all objects are created on the stack.

    because none of these objects leak memory, even though dlg has a parent:
    Qt Code:
    1. class dlgLogin : public QDialog
    2. {
    3. Q_OBJECT
    4. public:
    5. Ui::dlgLoginUi dui;
    6. dlgLogin()
    7. {
    8. dui.setupUi(this);
    9. dui.leUserName->setText("your revid");
    10. dui.leUserPassword->setText("");
    11. dui.leUserName->setFocus();
    12. dui.leUserName->selectAll();
    13. }
    14. };
    To copy to clipboard, switch view to plain text mode 
    Dialog does NOT have a parent. Look how you instantiated it

    Qt Code:
    1. dlgLogin dlg; // <- No parent
    To copy to clipboard, switch view to plain text mode 

    It's constructor does not event have a QWidget* 'parent' parameter, so there is no way to create a dlgLogin object with a parent (even if you wanted to).

    What makes you think that it has a parent?

    but homestead does not...
    Qt Code:
    1. class homestead : public QMainWindow
    2. {
    3. Q_OBJECT
    4. public:
    5. homestead(QWidget *parent = 0);
    6. ...
    To copy to clipboard, switch view to plain text mode 

    Right?
    Correct (but not for the reason that you have stated). Your homestead object does not have a parent, because you declared it like this:
    Qt Code:
    1. homestead ht;
    To copy to clipboard, switch view to plain text mode 

    If you wanted it to have a parent, you would have declared it like this:
    Qt Code:
    1. ...
    2. homestead ht(parent); // Parent is some QWidget*, declared further up
    To copy to clipboard, switch view to plain text mode 

    In both cases, the fact theat you declared your widgets with no parent is fine, because you are ensuring their destruction by declaring them on the stack (not as pointers allocated with 'new') and therefore, they are destroyed when they run out of scope.

  20. #20
    Join Date
    Jan 2006
    Location
    Lincoln, NE USA
    Posts
    177
    Thanks
    3
    Thanked 7 Times in 6 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Basic question on new and delete

    Quote Originally Posted by Chicken Blood Machine
    That would not even compile. None of the variables you mentioned are pointer variables, so how could you ever call delete on them? Your code (above) as listed will not leak any memory, because all objects are created on the stack.
    That I knew, I was just supposing that if they were created by "new" would it matter if they were deleted using the delete operator because they were going out of scope anyway if, as you say, the OS will always get the memory back.


    Dialog does NOT have a parent. Look how you instantiated it

    Qt Code:
    1. dlgLogin dlg; // <- No parent
    To copy to clipboard, switch view to plain text mode 

    It's constructor does not event have a QWidget* 'parent' parameter, so there is no way to create a dlgLogin object with a parent (even if you wanted to).

    What makes you think that it has a parent?
    Because it inherited from QDialog?
    class dlgLogin : public QDialog

    An ancestor isn't a parent?
    (I told you I was new to C++)

    Correct (but not for the reason that you have stated). Your homestead object does not have a parent, because you declared it like this:
    Qt Code:
    1. homestead ht;
    To copy to clipboard, switch view to plain text mode 

    If you wanted it to have a parent, you would have declared it like this:
    Qt Code:
    1. ...
    2. homestead ht(parent); // Parent is some QWidget*, declared further up
    To copy to clipboard, switch view to plain text mode 

    In both cases, the fact theat you declared your widgets with no parent is fine, because you are ensuring their destruction by declaring them on the stack (not as pointers allocated with 'new') and therefore, they are destroyed when they run out of scope.
    So, using "new" as shown below means that "ui.gridMultiProp" is a parent to *model ??
    Qt Code:
    1. QSqlQueryModel *model = new QSqlQueryModel(ui.gridMultiProp);
    To copy to clipboard, switch view to plain text mode 
    Pardon the dumb questions but you'll dealing with someone who has read perhaps too much and it's all jumbled up inside?
    It's amazing that I can, using QT, write the app I did and that it works.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.