Note that there are some explanatory texts on larger screens.

plurals
  1. POMemory Management with Command Pattern
    primarykey
    data
    text
    <p> So, I've got the following Command Pattern implementation, which is contained within a <code>std::map&lt;CString, IWrite*&gt; commandMap</code>:</p> <pre class="lang-cpp prettyprint-override"><code>class IWrite { protected: CStdioFile* fileWriter; public: IWrite(CStdioFile* _fileWriter) : fileWriter(_fileWriter) { } virtual ~IWrite() { } virtual BOOL exec() = 0; }; </code></pre> <p></p> <pre class="lang-cpp prettyprint-override"><code>class FloatWrite : public IWrite { private: float input; public: FloatWrite(CStdioFile* _fileWriter, float _input) : IWrite(_fileWriter), input(_input) { } BOOL exec() { CString fieldvalue; fieldvalue.Format("%f", input); fileWriter-&gt;WriteString(fieldvalue); return TRUE; } }; </code></pre> <p>The issue I'm having is that my static analysis tool complains that <code>fileWriter</code> is not freed or zeroed in the destructor of <code>IWrite</code>. However, by adding a <code>delete fileWriter</code> in the destructor, I get a memory access error when I delete the Command Pattern object in the map before calling <code>std::map.clear()</code> as below:</p> <pre class="lang-cpp prettyprint-override"><code>// free map memory for ( std::map&lt;CString, IWrite*&gt;::iterator mapItr = commandMap.begin(); mapItr != commandMap.end(); ++mapItr) { delete mapItr-&gt;second; } commandMap.clear(); </code></pre> <p>Am I approaching memory management incorrectly here? I have not done much work with STL maps, so I'm not familiar with an idiomatic approach.</p> <p>EDIT: How I add elements to the map:</p> <pre class="lang-cpp prettyprint-override"><code>void FooClass::initCommandMap(const MSG_DATA_STRUCT * msgdata) { // Write a float, foo commandMap[_T("foo")] = new FloatWrite(&amp;fileWriter, msgdata-&gt;foo); // Write an unsigned int, bar commandMap[_T("bar")] = new UIntWrite(&amp;fileWriter, msgdata-&gt;bar); // etc... } </code></pre> <p>This is called each time the user chooses to write out the data, so the <code>fileWriter</code> object used by the various <code>exec()</code>'s is current with the file selected by the user.</p> <p>Note that <code>CStdioFile fileWriter</code> is a member variable of <code>FooClass</code>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload