Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I must do a delete of a value but if the value has the new...

so

if (a = new Dialog)

i do the delete...otherwise I don't do the delete...how must I do?

What I have tried:

I tried:

if(a)
delete a;

but it doesn't work, i have a block of the program when a doesn't have the new
Posted
Updated 2-Oct-20 0:18am

The recipe is:"you shall always initialise your pointer" (with nullptr if you need to assign it later) then you may delete it or not, as appropriate.
Another approach would be using a smart pointer, this way no delete is needed.
Try, for instance:
C++
#include <iostream>
#include <memory>
using namespace std;

struct Dialog
{
  Dialog(){ cout << "Dialog ctor\n"; }
  ~Dialog(){ cout << "Dialog dtor\n";}
};

int main()
{
  {
    cout << "test case 1\n";
    Dialog * pdlg = new Dialog();
    if ( pdlg ) delete pdlg;
  }
  {
    cout << "test case 2\n";
    Dialog * pdlg{ nullptr };
    if ( pdlg ) delete pdlg;
  }
  {
    cout << "test case 3\n";
    auto spdlg = make_unique<Dialog>();
  }

  {
    cout << "test case 4\n";
    unique_ptr<Dialog> spdlg{};
  }
}
 
Share this answer
 
C++
a = new Dialog; // the result must be an object reference or nullptr.

// ...

if(a)
{
    delete a;
    a = nullptr;
}

The above should work.
 
Share this answer
 
If it is showing MFC dialog, just do this.

C++
CMyDialog dlg;
dlg.DoModal();
// no need to delete because is not new.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900