Deleting an object?

I'm accessing a memeber function of an object that has been deleted. My question is why the compiler didn't complain? I'm using Qt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <QDebug>
#include "myclass.h"

int main(int argc, char *argv[])
{
    QObject parent;
    MyClass *a, *b, *c;

    a = new MyClass("foo", &parent);
    b = new MyClass("ba-a-ar", &parent);
    c = new MyClass("baz", &parent);

    qDebug() << a->text()
             << " ("
             << a->getLengthOfText()
             << " )";
    a->setText(b->text());
    qDebug() << a->text()
             << " ("
             << a->getLengthOfText()
             << " )";

    delete a;
    return a->getLengthOfText();   // <-------

}
The compiler doesn't complain because it's a runtime issue. a->getLengthOfText() is perfectly legal syntax, so there is no compiler error.
So, is it safe to do that?
Not at all.
closed account (S6k9GNh0)
Perhaps an ideal compiler might warn you but it's not against the C++ standard to let that compile. It's your job to make sure your code doesn't do stupid things.
Last edited on
To help detect errors of this kind, use (ideally more than one) static analysis tools.
For instance: http://clang-analyzer.llvm.org/

To help prevent silly C-like errors of this kind, use RAII.
For instance: std::unique_ptr<MyClass> a( new MyClass("foo", &parent) ) ;
Topic archived. No new replies allowed.