[prev in list] [next in list] [prev in thread] [next in thread] 

List:       kde-devel
Subject:    The great destroy mystery.
From:       Gary Cramblitt <garycramblitt () comcast ! net>
Date:       2003-08-08 0:04:00
[Download RAW message or body]

In my object destructor, do I need to explicitly destroy object pointers
declared as member variables and initialized with _new_ or not?  I can't
find any consistent info on this. The C++ FAQ says that such objects are
"automagically" destroyed when the parent object is destroyed. Elsewhere
in the same FAQ, it says that one _must_ call delete for every new. ??
And if I explicitly destroy an object in my destructor, do I risk
destroying an object that has already been destroyed, thereby causing
havoc?  "Thinking in C++" has the following statement with regard to
_delete_:

"If the pointer you're deleting is zero, nothing will happen. For this
reason, people often recommend setting a pointer to zero immediately
after you delete it, to prevent deleting it twice. Deleting an object
more than once is definitely a bad thing to do, and will cause problems."

But the FAQ says that calling delete more than once on the same object
won't hurt.  "Thinking in C++" is strangely mute about "automagic"
destruction.

There was a thread in this list about a month ago that asked the same
question, but once again, there were conflicting answers.

As Denzel Washington said in _The Philadelphia Story_, can someone
please explain this to me like I were a two-year old?  Please?

Here's some sample code fragments to help the discussion along.

kspeak_part.h
-------------
class kspeakPart : public KParts::ReadOnlyPart
{
    Q_OBJECT
public:
    /**
     * Default constructor
     */
    kspeakPart(QWidget *parentWidget, const char *widgetName,
                    QObject *parent, const char *name);

    /**
     * Destructor
     */
    virtual ~kspeakPart();

protected:
    /**
     * This must be implemented by each part
     */
    virtual bool openFile();

private:
    KProcess *m_process;
};

kspeak_part.cpp
---------------
bool kspeakPart::openFile()
{
    // Create a new KProcess object.
    m_process = new KProcess;
    snip...
}

kspeakPart::~kspeakPart()
{
    // To delete or not to delete?
    delete m_process;

   // Maybe I should do this instead?
   if (m_process != NULL)
   {
        delete m_process;
        m_process = NULL;
   }
}

 
>> Visit http://mail.kde.org/mailman/listinfo/kde-devel#unsub to unsubscribe <<
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic