Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I do agree that <code>std::map&lt;string, string&gt;</code> will have advantages over <code>std::map&lt;char*, char*&gt;</code>. Specially having the key as value rather than pointer would provide the expected search/find results.</p> <p>But, sometimes we do need pointer in map definition specially in the value part when map’s value part is heavy object of a user defined class. By heavy object , I mean copy constructor of the class does a significant amount of work. In such scenarios, value part of the map should be a pointer. Using a raw pointer would leak the memory as mentioned above. Smart pointer would be a better choice ensuring no memory is leaked.</p> <p>Sample example: Consider the below class</p> <pre><code>class ABCD { public: ABCD(const int ab) : a(ab) {cout &lt;&lt; "Constructing ABC object with value : " &lt;&lt; a &lt;&lt; endl;} ~ABCD() {cout &lt;&lt; "Destructing ABC object with value : "&lt;&lt; a &lt;&lt; endl;} void Print() { cout &lt;&lt; "Value is : " &lt;&lt; a &lt;&lt; endl;} private: int a; }; </code></pre> <p>Consider the code where-in smart pointer of the above class is used:</p> <pre><code>{ std::map&lt;_tstring, std::shared_ptr&lt;ABCD&gt;&gt; myMap; _tstring key(_T("Key1")); myMap.insert(std::make_pair(key, std::make_shared&lt;ABCD&gt;(10))); auto itr = myMap.find(key); itr-&gt;second-&gt;Print(); myMap[key] = std::make_shared&lt;ABCD&gt;(20); itr = myMap.find(key); itr-&gt;second-&gt;Print(); } // myMap object is destroyed, which also calls the destructor of ABCD class </code></pre> <p>Output from above code is:</p> <pre><code>Constructing ABC object with value : 10 Value is : 10 Constructing ABC object with value : 20 Destructing ABC object with value : 10 Value is : 20 Destructing ABC object with value : 20 </code></pre>
 

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