Is there a memory leak

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • forrestarrow
    New Member
    • Sep 2007
    • 2

    Is there a memory leak

    Hi All,
    I just read an instereing article and want to test if there is a memory leak for the following code. The code is following:

    [code=cpp]
    #include <iostream>

    using namespace std;
    class A{
    public:
    A() { cout << " Constructor!\n" ; }
    ~A() { cout << "Destructor!\n" ; }

    };

    int main() {
    A * ptA = new A(* new A);
    delete ptA;
    return 0;
    }
    [/code]
    The output is,
    Constructor!
    Destructor!

    Should there be two objects created and destructed? Why only pari of output? Thanks.

    Best,
    Jason
    Last edited by Banfa; Sep 10 '07, 04:11 PM. Reason: Added [code]...[/code] round diagram to preserve the spacing
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    There are 2 objects created, however you create one of them through the copy constructor (provided by default by the compiler) so you get not output message for it.

    Since you do not store the pointer returned from (* new A) you can not delete it, this object is never deleted and so you get a memory leak.

    When you call new you have to explicitly call delete.

    What this means is that the output you get is the construct message of 1 object and the delete message of the other.

    Comment

    Working...