CFD Online Logo CFD Online URL
www.cfd-online.com
[Sponsors]
Home > Forums > Software User Forums > OpenFOAM > OpenFOAM Programming & Development

[Memory Leak] Is this a correct usage of autoPtr?

Register Blogs Community New Posts Updated Threads Search

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old   January 24, 2017, 12:09
Default [Memory Leak] Is this a correct usage of autoPtr?
  #1
Senior Member
 
floquation's Avatar
 
Kevin van As
Join Date: Sep 2014
Location: TU Delft, The Netherlands
Posts: 252
Rep Power: 20
floquation will become famous soon enough
If I have the following snippet in the constructor of my class:
Code:
Foam::foo::foo(
    const dictionary& dictName
    (...)
)
{
    (...)
    // copy the input dictionary to ensure its existence
    // that is, it may go out-of-scope elsewhere and therefore seize to exist inside this class --> segmentation fault
    dict_ = autoPtr<dictionary>(new dictionary(dictName));
    (...)
}
where dict_ is defined in the header file as:
Code:
(...)
autoPtr<dictionary> dict_;
(...)
Just to make sure that my understanding is correct:
Is there a memory leak if this class gets disposed of?

Hypothesis:
When this class is disposed of, the destructor of all its entities are automatically called (right?). This includes the entity "dict_".
"dict_", being an autoPtr, should automatically take care of the data pointed at by the pointer it owns. It owns the pointer, because it was declared with the "new" statement inside its constructor argument.
floquation is offline   Reply With Quote

Old   January 25, 2017, 07:33
Default Solved
  #2
Senior Member
 
floquation's Avatar
 
Kevin van As
Join Date: Sep 2014
Location: TU Delft, The Netherlands
Posts: 252
Rep Power: 20
floquation will become famous soon enough
Solved: Above hypothesis was correct.
I designed a way to test this, by writing a small new class:

Code:
#include "dictionary.H"

namespace Foam
{

class kvadictionary
:
    public dictionary
{

public:

    kvadictionary(const dictionary& dict)
    :
    dictionary(dict)
    {
        Info << "kvadictionary constructor" << endl;
    }

    ~kvadictionary(){
        Info << "kvadictionary destructor" << endl;
    }

};

}
And changing the autoPtr constructor call to:
Code:
dict_ = autoPtr<dictionary>(new kvadictionary(dictName));
The result is a message when the dictionary (i.e. the object owned by the autoPtr) is disposed of:
Code:
foo destructor called
kvadictionary destructor
floquation is offline   Reply With Quote

Reply


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Moving mesh Niklas Wikstrom (Wikstrom) OpenFOAM Running, Solving & CFD 122 June 15, 2014 06:20


All times are GMT -4. The time now is 08:32.