<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Reflections of my thoughts... &#187; C++</title>
	<atom:link href="http://codereflect.com/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://codereflect.com</link>
	<description>on programming tips and trending topics...</description>
	<lastBuildDate>Wed, 08 Feb 2012 08:58:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>C++: Erase-Remove Idiom</title>
		<link>http://codereflect.com/2011/11/22/c-erase-remove-idiom/</link>
		<comments>http://codereflect.com/2011/11/22/c-erase-remove-idiom/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 13:10:10 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[STL]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Visual C++]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1832</guid>
		<description><![CDATA[Erase-remove idiom is a common technique to eliminate the elements from a C++ STL container which satisfies a particular condition. We can do the hand written loop to remove the elements from the container. For e.g. if you want to remove an element vector you can do something as below. (note erasing element from a [...]]]></description>
			<content:encoded><![CDATA[<p>Erase-remove idiom is a common technique to eliminate the elements from a C++ STL container which satisfies a particular condition.</p>
<p>We can do the hand written loop to remove the elements from the container. For e.g. if you want to remove an element vector you can do something as below. (note erasing element from a C++ container within a standard for or while loop with simple iterator++ will end up undefined result)</p>
<pre>
vector<int>::iterator it = vec.begin();
while(it != vec.end())
     if( *it == 5 )
         it = vec.erase(it); // Remove and take the return of the erase function to safely reassign
     else
         ++it;
</pre>
<p>The above code is simple as it appears, it simply iterate through the elements and find if a match there for the value then remove it from the container. And it takes back the value returned form <code>erase</code> where it returns the iterator of the next element. If no more elements, it will <code>vector::end</code> </p>
<p>Now, the containers will have different implementations for the same function. A <code>map::erase</code> return <code>void</code>. So it&#8217;s difficult to give a single and easy strategy for each type of containers.</p>
<p><a href="http://www.cplusplus.com/reference/algorithm/remove/" target="_blank"><code>remove</code></a> is a handy function defined in <code>algorthm</code> It&#8217;s easy to get confused to know what it does and distinguish between <code>erase</code>. <code>remove</code> remove (move) the elements from the given range. Mostly push it towards the end of the container. The function returns an iterator to the location where the moved elements located within the container. It essentially won&#8217;t remove the elements as such from the container. Here is the sample demo of using <code>remove</code></p>
<pre>
// remove algorithm example
#include <algorithm>
using namespace std;

int main ()
{
  int data[] = {10,20,30,30,20,10,10,20};      // 10 20 30 30 20 10 10 20

  // bounds of range:
  int* pbegin = data;                          // ^
  int* pend = data+sizeof(data)/sizeof(int);   // ^                       ^

  pend = remove (pbegin, pend, 20); // 10 30 30 10 10 ?  ?  ?
                                    // ^              ^

  return 0;
}
</pre>
<p>Now this handy function has an alternative version to give a comparator function which can accept the object of the type specified for the container. Inside the function, you can make decision to remove or not by specifying in the return value. In simple words, rather giving a comparison hard coded value, we&#8217;ll give a function to make decision for us. <a href="http://www.cplusplus.com/reference/algorithm/remove_if/" target="_blank">See the documentation and example here.</a></p>
<p>Erase-Remove tequenique is accomplished in following ways.<br />
1. Move the elements to be removed to the end with the help of <code>remove</code> function<br />
2. Take the return of <code>remove</code> and pass to the <code>erase</code> function as beginning and containers::end as end.<br />
3. Finally the contianer will contains the elements which are not satisfying the comparator function/value.</p>
<pre>
#include <vector> // the general-purpose vector container
#include <algorithm> // remove and remove_if

bool is_odd(int i) { // unary predicate returning true if and only if the argument is odd
  return i % 2;
}
bool is_even(int i) { // unary predicate returning true if and only if the argument is even
  return !is_odd(i);
}

int main() {
  using namespace std;
  int elements[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  // create a vector that holds the numbers from 0-9.
  vector<int> v(elements, elements + 10); 

  // use the erase-remove idiom to remove all elements with the value 5
  v.erase(remove(v.begin(), v.end(), 5), v.end()); 

  // use the erase-remove idiom to remove all odd numbers
  v.erase( remove_if(v.begin(), v.end(), is_odd), v.end() );

  // use the erase-remove idiom to remove all even numbers
  v.erase( remove_if(v.begin(), v.end(), is_even), v.end() );
}
</pre>
<p>Reference:<br />
<a href="http://en.wikipedia.org/wiki/Erase-remove_idiom" target="_blank">Erase-remove idiom</a></p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/11/22/c-erase-remove-idiom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Analysis &#8211; Visual C++ 2011</title>
		<link>http://codereflect.com/2011/11/10/code-analysis-visual-c-2011/</link>
		<comments>http://codereflect.com/2011/11/10/code-analysis-visual-c-2011/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 19:20:52 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[C++ 0x]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Visual Studio 2011]]></category>
		<category><![CDATA[Code analysis]]></category>
		<category><![CDATA[VS2011]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1778</guid>
		<description><![CDATA[Microsoft finally including code analysis to detect the problematic code that could lead to crash and create security woes. •Fixing a bug early avoids wasted time debugging strange crashes or reliability issues later on. •Fixing a bug early avoids resetting/repeating testing after a bug is fixed late in the development cycle. •Fixing a bug early [...]]]></description>
			<content:encoded><![CDATA[<p>Microsoft finally including code analysis to detect the problematic code that could lead to crash and create security woes.</p>
<p>•Fixing a bug early avoids wasted time debugging strange crashes or reliability issues later on.<br />
•Fixing a bug early avoids resetting/repeating testing after a bug is fixed late in the development cycle.<br />
•Fixing a bug early avoids the complexities associated with fixing it if it is exposed after the application ships.</p>
<p>The Security Science team with the Microsoft Security Engineering Centre (MSEC) worked closely with the Visual Studio Code Analysis team to ensure that the Visual Studio Developer Preview includes as many of the SDL mandatory C/C++ Code Analysis warnings as possible. These are the security-related warnings that Microsoft considers critical to fix for internal C/C++ software development. </p>
<p>This feature is included in Visual Studio 2011 Express as well.</p>
<p><a href="http://blogs.msdn.com/b/sdl/archive/2011/10/19/code-analysis-for-all.aspx" target="_blank">read more</a></p>
<p><iframe style="height:544px;width:960px" src="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-100T/player?w=960&#038;h=544" frameBorder="0" scrolling="no" ></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/11/10/code-analysis-visual-c-2011/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++: Why new to be used only when unavoidable?</title>
		<link>http://codereflect.com/2011/09/07/why-new-to-be-used-when-unavoidable/</link>
		<comments>http://codereflect.com/2011/09/07/why-new-to-be-used-when-unavoidable/#comments</comments>
		<pubDate>Wed, 07 Sep 2011 13:22:02 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Win32]]></category>
		<category><![CDATA[Memory management]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1710</guid>
		<description><![CDATA[Those who program with modern languages like C# or Java has a tendency to use each and every object declaration in C++ with new. Why we should avoid using new as much as possible? Unlike Java/C#, C++ doesn&#8217;t employ any memory manager by its own to control the life time of dynamically allocated objects (using [...]]]></description>
			<content:encoded><![CDATA[<p>Those who program with modern languages like C# or Java has a tendency to use each and every object declaration in C++ with new. Why we should avoid using new as much as possible?</p>
<div>
<ul>
<li>Unlike Java/C#, C++ doesn&#8217;t employ any memory manager by its own to control the life time of dynamically allocated objects (using new).</li>
<li>C++ using operating system routines to allocate the memory and too much new/delete could fragment the available memory. The architecture and management of a garbage collector is entirely different from a native perspective.</li>
<li>Improper memory management could lead memory leaks and it&#8217;s really hard to track.</li>
<li>The stack objects implementation is foolproof.</li>
<li>With any application, if large chunk of memory is frequently being used, it&#8217;s advised to pre-allocate it and release when not required.</li>
<li>The downside of using stack objects are, it creates intermediate copies of objects on returning, passing to functions (by value) etc. But the memory management of C#/Java helps the (JIT)compiler to manage these tasks memory efficient. However modern C++ compilers are well aware of these situations and they&#8217;ve optimized for performance.</li>
<li>It&#8217;s really tedious in C++ if the memory being allocated and released in two different places. The responsibility for release is always a question and mostly we rely on some commonly accessible pointers, stack objects (maximum possible) and techniques like auto_ptr, shared_ptr (reference counted pointers &#8211; C++0x) (RAII objects)</li>
<li>The best thing in C++ is that, you&#8217;ve control over the memory and the worst thing is that you will not have any control over the memory if we employ an improper memory management for the application. The crashes caused due to memory corruptions are the nastiest one in the world.</li>
</ul>
</div>
<div>In C++, the STL containers mostly rely on dynamically memory. In a way or other, they&#8217;re RAII objects, which automatically releases the resources upon destruction. In addition to that, it eases the programmers life by providing useful interfaces (services) to make best of OOP, (like operator+= with string objects, push_back function with containers, easy copying of containers by assignment etc.). It&#8217;s a good practice to make best use of the proven library classes/functions/algorithms to make your program work efficient. Also operating system memory routines are costly to handle. Hence there will be  a performance hit on using dynamic memory allocation.</div>
<div>Of course we can&#8217;t say a stack object is completely allocated in stack to improve the performance. Consider the example of std::string class which holds the actual string content in the heap memory but the advantage is that, the memory is automatically managed on reassigning, concatenation, destruction etc.</div>
<div>But there are situations where we&#8217;ve to use the dynamic memory allocations like reading  bytes from files where we don&#8217;t know the size of the buffer which we required to pass the read function. In such situations, either we&#8217;ve to use the dynamic memory and handle the it our self or, use the proven classes like ofstream/ifstream etc with required objects (like std::string) to read the content and thus let them manage the memory automatically.</div>
<div>See further on my answer in <a href="http://stackoverflow.com/questions/6500313/in-c-why-should-new-be-used-as-little-as-possible/6501080#6501080" target="_blank">StackOverflow.com</a></div>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/09/07/why-new-to-be-used-when-unavoidable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WinDBG &#8211; Visualizing STL containers and strings</title>
		<link>http://codereflect.com/2011/08/16/windbg-visualizing-stl-containers-and-strings/</link>
		<comments>http://codereflect.com/2011/08/16/windbg-visualizing-stl-containers-and-strings/#comments</comments>
		<pubDate>Tue, 16 Aug 2011 06:33:18 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[STL]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[WinDBG]]></category>
		<category><![CDATA[C++.STL]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1676</guid>
		<description><![CDATA[With the help of STL extension, this extension can&#8217;t visualize each and every containers or classes in STL, rather it displays the mostly used string, wstring, vector, list for more information give !stl -? in WinDBG input or check in the help file. See the example below and the output in the debugger console. // [...]]]></description>
			<content:encoded><![CDATA[<p>With the help of STL extension, this extension can&#8217;t visualize each and every containers or classes in STL, rather it displays the mostly used string, wstring, vector<[w]string>, list<[w]string></p>
<p>for more information give <code>!stl -?</code> in WinDBG input or check in the help file.<br />
See the example below and the output in the debugger console.</p>
<pre>
// SampleSTL.cpp : Defines the entry point for the console application.
// Compiled with Microsoft Visual C++ 9.0 compiler

#include "stdafx.h"
#include <vector>
#include <string>
#include
<list>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

	string str1("Quick");
	string str2("Brown" );

	string str3 = str1 + " " + str2;

	vector<string> vec;

	vec.push_back(str1);
	vec.push_back(str2);
	vec.push_back(str3);

	list<string> lst;

	lst.push_back( str1 );
	lst.push_back( str2 );
	lst.push_back( str3 );

	for( vector<string>::iterator iter = vec.begin(); iter != vec.end(); ++iter)
		cout << (*iter).c_str() << endl;

	cout <<endl<<endl;

	for( list<string>::iterator iter = lst.begin(); iter != lst.end(); ++iter)
		cout << (*iter).c_str() << endl;

	return 0;
}
</pre>
<p>WinDGB output</p>
<pre>
0:000> !stl str1
[da 0x16fb18]
0016fb18  "Quick"

0:000> !stl str2
[da 0x16faf0]
0016faf0  "Brown"

0:000> !stl str3
[da 0x16fac8]
0016fac8  "Quick Brown"

0:000> !stl vec
	Element 0
[da 0x558358]
00558358  "Quick"
	Element 1
[da 0x558378]
00558378  "Brown"
	Element 2
[da 0x558398]
00558398  "Quick Brown"

0:000> !stl lst
The list has 00000003 elements
	Element 0
[da 0x558400]
00558400  "Brown"
	Element 1
[da 0x558468]
00558468  "Quick Brown"
	Element 2
[da 0xffffffffcdcdcdcd]
cdcdcdcd  "????????????????????????????????"
cdcdcded  "????????????????????????????????"
cdcdce0d  "????????????????????????????????"
cdcdce2d  "????????????????????????????????"
cdcdce4d  "????????????????????????????????"
cdcdce6d  "????????????????????????????????"
cdcdce8d  "????????????????????????????????"
cdcdcead  "????????????????????????????????"
cdcdcecd  "????????????????????????????????"
cdcdceed  "????????????????????????????????"
cdcdcf0d  "????????????????????????????????"
cdcdcf2d  "????????????????????????????????"
</pre>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/08/16/windbg-visualizing-stl-containers-and-strings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NaCL + Pepper (Salt &#8216;N&#8217; Pepper) &#8211; Google Chrome Embraces C++</title>
		<link>http://codereflect.com/2011/08/12/nacl-pepper-salt-n-pepper-google-chrome-embraces-c/</link>
		<comments>http://codereflect.com/2011/08/12/nacl-pepper-salt-n-pepper-google-chrome-embraces-c/#comments</comments>
		<pubDate>Fri, 12 Aug 2011 02:48:21 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[browsers]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[chrome]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1653</guid>
		<description><![CDATA[Google announces the integration of Native Client into Chrome. Native Client allows C and C++ code to be seamlessly executed inside the browser with security restrictions similar to JavaScript. Native Client apps use Pepper, a set of interfaces that provide C and C++ bindings to the capabilities of HTML5. As a result, developers can now [...]]]></description>
			<content:encoded><![CDATA[<p>Google announces the integration of Native Client into Chrome. Native Client allows C and C++ code to be seamlessly executed inside the browser with security restrictions similar to JavaScript. Native Client apps use Pepper, a set of interfaces that provide C and C++ bindings to the capabilities of HTML5. As a result, developers can now leverage their native code libraries and expertise to deliver portable, high performance web apps. </p>
<p><iframe width="640" height="390" src="http://www.youtube.com/embed/nP8Mo0jGQDk" frameborder="0" allowfullscreen></iframe></p>
<p><a href="http://www.readwriteweb.com/cloud/2011/08/google-officially-announces-cc.php" target="_blank">See a better scoop here</a></p>
<p>Yea browsers are powerful than ever! Long live C++</p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/08/12/nacl-pepper-salt-n-pepper-google-chrome-embraces-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++: How to clear the input stream?</title>
		<link>http://codereflect.com/2011/06/29/c-how-to-clear-the-input-stream/</link>
		<comments>http://codereflect.com/2011/06/29/c-how-to-clear-the-input-stream/#comments</comments>
		<pubDate>Wed, 29 Jun 2011 09:39:28 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[C++ 0x]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1521</guid>
		<description><![CDATA[What do you expect from the following program? char x = 0; std::cout &#60;&#60; &#34;Enter a character: &#34; &#60;&#60; std::endl; std::cin &#62;&#62; x; std::cout &#60;&#60; &#34;You entered &#34; &#60;&#60; x &#60;&#60; std::endl; int y; std::cout &#60;&#60; &#34;Enter a number: &#34; &#60;&#60; std::endl; std::cin &#62;&#62; y; std::cout &#60;&#60; &#34;You entered &#34; &#60;&#60; y &#60;&#60; std::endl; If [...]]]></description>
			<content:encoded><![CDATA[<p>What do you expect from the following program?</p>
<pre>
char x = 0;
std::cout &lt;&lt; &quot;Enter a character: &quot; &lt;&lt; std::endl;
std::cin &gt;&gt; x;
std::cout &lt;&lt; &quot;You entered &quot; &lt;&lt; x &lt;&lt; std::endl;

int y;
std::cout &lt;&lt; &quot;Enter a number: &quot; &lt;&lt; std::endl;
std::cin &gt;&gt; y;
std::cout &lt;&lt; &quot;You entered &quot; &lt;&lt; y &lt;&lt; std::endl;
</pre>
<p>If you enter multiple characters for first input (cin >> x), the stream will take the first character and make it not to prompt for the next input as the input buffer contains additional data. How to deal with such a situation?</p>
<p>There&#8217;s a high chance to misinterpret cin.clear() which is actually supposed to sets a new value for the error control state.  Standard C/C++ input streams are buffered. The keypresses are buffered by operating system, not by the program. If you&#8217;re sure that unnecessary data is present in input stream. You can make use of <a href="http://www.cplusplus.com/reference/iostream/istream/ignore/">istream::ignore</a> function to extract and discard the remaining data in the input stream. (Alternatively, you can recursively call cin.get() to make sure that all the data in the buffer are consumed). See the snippet below</p>
<pre>
char x = 0;
std::cout &lt;&lt; &quot;Enter a character: &quot; &lt;&lt; std::endl;
std::cin &gt;&gt; x;
std::cout &lt;&lt; &quot;You entered &quot; &lt;&lt; x &lt;&lt; std::endl;

// Clear the stream
std::cin.clear();
std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), &#039;\n&#039;);
// alternative method
// while( !cin.eof() &amp;&amp; cin.get() == &#039;\n&#039; );

int y;
std::cout &lt;&lt; &quot;Enter a number: &quot; &lt;&lt; std::endl;
std::cin &gt;&gt; y;
std::cout &lt;&lt; &quot;You entered &quot; &lt;&lt; y &lt;&lt; std::endl;
</pre>
<p>2010-06-29 &#8211; 4:46 PM IST &#8211; Updated Angelo&#8217;s comment</p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/06/29/c-how-to-clear-the-input-stream/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to check mouse button status without message handler?</title>
		<link>http://codereflect.com/2011/06/10/how-to-check-mouse-button-status-without-message-handler/</link>
		<comments>http://codereflect.com/2011/06/10/how-to-check-mouse-button-status-without-message-handler/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 12:55:31 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[MFC]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Visual C++]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Mouse input]]></category>
		<category><![CDATA[Win32]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1495</guid>
		<description><![CDATA[We can map WM_LBUTTON or WM_RBUTTON down to know whether user has pressed the left or right button respectively on top of the window or not. But sometimes, we have to know this information while we&#8217;re processing other handlers like painting/drawing the window. #define SHIFTED 0x8000 void GetMouseButtonState() { if ((GetKeyState(VK_LBUTTON) &#038; SHIFTED)) { printf( [...]]]></description>
			<content:encoded><![CDATA[<p>We can map WM_LBUTTON or WM_RBUTTON down to know whether user has pressed the left or right button respectively on top of the window or not. But sometimes, we have to know this information while we&#8217;re processing other handlers like painting/drawing the window.</p>
<pre>
#define SHIFTED 0x8000
void GetMouseButtonState()
{
   if ((GetKeyState(VK_LBUTTON) &#038; SHIFTED))
   {
      printf( "Left button is pressed" );
   }

   if ((GetKeyState(VK_RBUTTON) &#038; SHIFTED))
   {
      printf( "Right button is pressed" );
   }
}
</pre>
<p>Please note that this information is a system wide information. By knowing this status doesn&#8217;t mean that the button is pressed on top of your window. For that you will have to know the current cursor position using GetCursorPosition and check if it&#8217;s within the Window Rect or not.</p>
<p>You can see the similar keyboard sample at MSDN website. &#8211; <a href="http://msdn.microsoft.com/en-us/library/ms646268%28v=vs.85%29.aspx#displaying_input">Using Keyboard Input</a></p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/06/10/how-to-check-mouse-button-status-without-message-handler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++: Is it safe to delete a NULL pointer?</title>
		<link>http://codereflect.com/2011/06/09/is-it-safe-to-delete-a-null-pointer/</link>
		<comments>http://codereflect.com/2011/06/09/is-it-safe-to-delete-a-null-pointer/#comments</comments>
		<pubDate>Thu, 09 Jun 2011 02:39:11 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[C++ 0x]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1395</guid>
		<description><![CDATA[Usually we&#8217;ve seen people writing source code which check against NULL and delete it. if( ptr ) delete ptr; As per the standard it&#8217;s safe to delete a NULL pointer because the operator delete function will simply return if the pointer is NULL. But this has the cost of calling operator delete function, comparison operation [...]]]></description>
			<content:encoded><![CDATA[<p>Usually we&#8217;ve seen people writing source code which check against NULL and delete it.</p>
<pre>
if( ptr )
delete ptr;
</pre>
<p>As per the standard it&#8217;s safe to delete a NULL pointer because the operator delete function will simply return if the pointer is NULL. But this has the cost of calling operator delete function, comparison operation and stack unwinding and return. But these performance gains are actually negligible because</p>
<ul>
<li>The performance gain only matters if you&#8217;re too much worried about the minute performance. This will be visible if frequent allocations and deallocations are made during the run time. But again, it&#8217;s not really a good design to make frequent allocations and de allocation because it may cause the fragmentation in memory and reduce the performance.</li>
<li>In usual programming scenarios memory will be freed when object is release/Application terminates. In that sense this super minute performance can be ignored.</li>
<li>Usually the memory will be allocated. It&#8217;s very rare that the pointer become NULL. In that case the additional comparison is an overhead.</li>
<li>Improves the readability of the code and avoid unnecessary checkings.</li>
<li>Reduce the code size especially there are too many delete code is there in the project.</li>
</ul>
<p>But in some scenarios NULL pointer check is required to do the error logging for better troubleshooting. Also implement comparison if there&#8217;s really very high probability of NULL pointers (It&#8217;s usually rare in normal scenarios)</p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/06/09/is-it-safe-to-delete-a-null-pointer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to save Icon as bitmap?</title>
		<link>http://codereflect.com/2011/05/05/how-to-save-icon-as-bitmap/</link>
		<comments>http://codereflect.com/2011/05/05/how-to-save-icon-as-bitmap/#comments</comments>
		<pubDate>Thu, 05 May 2011 12:06:55 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Visual C++]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[bitmap]]></category>
		<category><![CDATA[icon]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tweak]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1428</guid>
		<description><![CDATA[Icons are being a bit mysterious comparing to bitmaps. Now how we can save and icon to bitmap. There are several methods to do this. Here&#8217;s a simple tweak to save it using memory DC. void SaveBitmapToFile( BYTE* pBitmapBits, LONG lWidth, LONG lHeight,WORD wBitsPerPixel, LPCTSTR lpszFileName ) { BITMAPINFOHEADER bmpInfoHeader = {0}; // Set the [...]]]></description>
			<content:encoded><![CDATA[<p>Icons are being a bit mysterious comparing to bitmaps. Now how we can save and icon to bitmap. There are several methods to do this. Here&#8217;s a simple tweak to save it using memory DC.</p>
<pre>
void SaveBitmapToFile( BYTE* pBitmapBits, LONG lWidth, LONG lHeight,WORD wBitsPerPixel, LPCTSTR lpszFileName )
{
    BITMAPINFOHEADER bmpInfoHeader = {0};
    // Set the size
    bmpInfoHeader.biSize = sizeof(BITMAPINFOHEADER);
    // Bit count
    bmpInfoHeader.biBitCount = wBitsPerPixel;
    // Use all colors
    bmpInfoHeader.biClrImportant = 0;
    // Use as many colors according to bits per pixel
    bmpInfoHeader.biClrUsed = 0;
    // Store as un Compressed
    bmpInfoHeader.biCompression = BI_RGB;
    // Set the height in pixels
    bmpInfoHeader.biHeight = lHeight;
    // Width of the Image in pixels
    bmpInfoHeader.biWidth = lWidth;
    // Default number of planes
    bmpInfoHeader.biPlanes = 1;
    // Calculate the image size in bytes
    bmpInfoHeader.biSizeImage = lWidth* lHeight * (wBitsPerPixel/8);

    BITMAPFILEHEADER bfh = {0};
    // This value should be values of BM letters i.e 0x4D42
    // 0x4D = M 0×42 = B storing in reverse order to match with endian
    bfh.bfType=0x4D42;
    /* or
    bfh.bfType = ‘B’+(‘M’ &lt;&lt; 8);
    // &lt;&lt;8 used to shift ‘M’ to end
    */
    // Offset to the RGBQUAD
    bfh.bfOffBits = sizeof(BITMAPINFOHEADER) + sizeof(BITMAPFILEHEADER);
    // Total size of image including size of headers
    bfh.bfSize = bfh.bfOffBits + bmpInfoHeader.biSizeImage;
    // Create the file in disk to write
    HANDLE hFile = CreateFile( lpszFileName,GENERIC_WRITE, 0,NULL,

                               CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,NULL);

    if( !hFile ) // return if error opening file
    {
        return;
    }

    DWORD dwWritten = 0;
    // Write the File header
    WriteFile( hFile, &amp;bfh, sizeof(bfh), &amp;dwWritten , NULL );
    // Write the bitmap info header
    WriteFile( hFile, &amp;bmpInfoHeader, sizeof(bmpInfoHeader), &amp;dwWritten, NULL );
    // Write the RGB Data
    WriteFile( hFile, pBitmapBits, bmpInfoHeader.biSizeImage, &amp;dwWritten, NULL );
    // Close the file handle
    CloseHandle( hFile );
}

void CLoadIconSampleDlg::OnBnClickedButtonSaveIcon()
{
	// Loading resource from DLL.
	HMODULE h = LoadLibrary( L&quot;myresource.dll&quot; );

	if( !h )
	{
		MessageBox( L&quot;Failed to load library&quot; );
		return;
	}

	INT id = GetDlgItemInt( IDC_EDIT1 );
	m_hLoadedIcon = LoadIcon( (HINSTANCE) h , MAKEINTRESOURCE( id ) );

	CBitmap bmpSave;
	CClientDC dc(this);
	bmpSave.CreateCompatibleBitmap( &amp;dc, 32, 32 );

	CDC dcMem;
	dcMem.CreateCompatibleDC( &amp;dc );
	dcMem.SelectObject( &amp;bmpSave );
	dcMem.DrawIcon( 0, 0, m_hLoadedIcon );

	BITMAP bmpInfo;
	bmpSave.GetBitmap( &amp;bmpInfo );

	int size = bmpInfo.bmHeight* bmpInfo.bmWidth * (bmpInfo.bmBitsPixel / 8 );
	unsigned char* pBytes = new unsigned char[size];
	bmpSave.GetBitmapBits( size, pBytes );
	SaveBitmapToFile( pBytes, 32, 32, bmpInfo.bmBitsPixel, _T( &quot;C:\\temp\\temp.bmp&quot; ));
	delete []pBytes;

	FreeLibrary( h );
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/05/05/how-to-save-icon-as-bitmap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>const to data and pointer</title>
		<link>http://codereflect.com/2011/02/23/const-to-data-and-pointer/</link>
		<comments>http://codereflect.com/2011/02/23/const-to-data-and-pointer/#comments</comments>
		<pubDate>Wed, 23 Feb 2011 08:57:52 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Visual C++]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1424</guid>
		<description><![CDATA[This is a fundamental thing that every C++ programmers must know. const to data This is the simplest form of pointer definition that we always do. const int* data3 = arr2; // Const to data data3[0] = 55;  // ERROR: Data can't be changed data3 = arr1;    // Success:  Can't change the pointer to somewhere [...]]]></description>
			<content:encoded><![CDATA[<p>This is a fundamental thing that every C++ programmers must know.</p>
<h2>const to data</h2>
<p>This is the simplest form of pointer definition that we always do.</p>
<pre>
const int* data3 = arr2; // Const to data
data3[0] = 55;  // ERROR: Data can't be changed
data3 = arr1;    // Success:  Can't change the pointer to somewhere else
</pre>
<p>Here the data is can’t changed using data3 pointer. but the pointer itself can be modified and can point to some other location.</p>
<p>Usually  we don’t care even if pass the pointer to some function and that  pointer changes to some other location, as the function parameters  points to same location but the pointer is a copy of actual parameter.  But things may go different if we wrongly pass reference to function  parameters even it’s const. So we’ve to take care this while designing  the interfaces.</p>
<pre>
void Foo(  LPCTSTR&amp; lpszValue )
{
	lpszValue = _T( &quot;codereflect.com&quot; );
}

int _tmain(int argc, _TCHAR* argv[])
{
	LPCTSTR sz = NULL;
	Foo(sz);
	_tprintf( sz );
	return 0;
}
</pre>
<h2>const to pointer</h2>
<p>In this form of usage, the pointer can’t be changed to some location but the data can be changed.</p>
<pre>
int* const data2 = arr2; // const to pointer
data2 = arr1;    // Can't change the pointer to somewhere else
data2[0] = 55;  // SUCCESS: Data can be changed
</pre>
<h2>const to both data and pointer</h2>
<p>This is the goodness of both <img src='http://codereflect.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . The most secure pointer.</p>
<pre>
const int* const data1 = arr1; // Const to both pointer and data
data1 = arr2;    // ERROR: can't change the pointer
data1[0] = 100; // ERROR: can't change the data
</pre>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/02/23/const-to-data-and-pointer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

