Archive for May, 2008

Function Objects or simply Functors.

0


A function object is an ordinary class object with operator () overloaded. The specialty of functor is that the object can also act as function calls. But the power of a functor is – it can hold state.


See a sample code snippet for implementing a functor which compares two strings – with and with out case sensitive.

class Compare
{
public:
    // Constructor.
    Compare()
        : m_CaseSensitive(true)
    {}

    // overloaded () operator.
    BOOL operator()( CString& csString1, CString& csString2)
    {
        if( m_CaseSensitive )
        {
            // Case sensitive comparison.
            return csString1 == csString2;
        }
        else
        {
            // Non Case sensitive comparison.
            return (csString1.CompareNoCase( csString2 ) == 0) ? TRUE : FALSE;
        }
    }

    // Set the comparison.
    void SetComparisonCaseSensitive( bool CaseSensitive )
    { m_CaseSensitive = CaseSensitive; }

private:
    bool m_CaseSensitive;
};

void CompareStrings()
{
    CString csString1 = _T("Hello");
    CString csString2 = _T("hello");

    // The functor.
    Compare CompareStrings;

    // Demo of case sensitive comparison.
    BOOL bCaseSensitiveComparison = CompareStrings( csString1,
                                                    csString2);

    // non Case sensitive comparison.
    CompareStrings.SetComparisonCaseSensitive( false );
    // Demo of case sensitive comparison.
    BOOL bNonCaseSensitiveComparison = CompareStrings( csString1,
                                                       csString2);
}

In the code snippet, a string comparison is implemented by using a functor. Ideally if you want the string comparison to be able to handle both case sensitive and non-case sensitive comparisons, you’ve to use some boolean values globally or should pass it as function parameters. Or else you’ve to implement two different functions to implement both of them.

Here comes the real power of a functor. Since Its a class, can hold parameters. So that you can avoid global variables, may be some function parameters etc. Try functors… its fun!


Don’t think that functors is a new feature introduced by C++. Functors exists long before the days of C++ :) One of the early languages that implemented functors was SmallTalk.


Targeted Audience – Intermediate.

How to mark your file for deletion after next reboot?

0


You might have seen, while un-installing some applications, the uninstaller says – “Some files remains and will be removed after next reboot”. How they can mark a file to be deleted after next restart?


The answer is MoveFileEx(). The MoveFileEx() have a special flag MOVEFILE_DELAY_UNTIL_REBOOT. By specifying it, the file will be marked for deletion during the next reboot. See the sample code snippet.

void MarkFileForDeletion(CString csFileName )
{
    MoveFileEx( csFileName, // Source File.
                0, // Destination as null.
                MOVEFILE_DELAY_UNTIL_REBOOT );
}


Actually, the MoveFileEx(), places the filename pair in the registry at – HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations. The PendingFileRenameOperations is of type REG_MULTI_SZ which can hold multiple strings. So that it can hold multiple pairs of source-destination filenames.


The MoveFileEx() is only applicable for Windows NT family. For Windows 95/98/Me you’ve to modify the WININIT.INI file. In that file, you’ve to modify the [rename] section. Since an old 95 box is not available, i couldn’t try it. If you have, just try and let me know!


Targeted Audience – Intermediate.

How to avoide BOOL to bool performance warning?

4


Many of the windows apis are using BOOL for boolean value which is actually a typedef of int. Its been used, because during old C days bool was not a built-in datatype. Now a days since C++ supports built-in bool, often we need to convert the BOOL to bool. For instance see code snippet below

BOOL bResult = FALSE;
...
bool bReturnValue = bResult;

But it will give you a perfoamnce warning – “warning C4800: ‘int’ : forcing value to bool ‘true’ or ‘false’ (performance warning)”. Because internally an int is converted to bool. But since our clients need “0 errors, 0 warnings” we’ve to avoid this warning. Its pretty simple.


you can make use of the operator != which will return bool. See the code snippet below.

BOOL bResult = FALSE;
...
bool bReturnValue = (bResult != FALSE);

Another interesting one is it can be used to reduce code unwanted code blots. See the following code block. Its a typical usage by most of us.

bool Function()
{
    // Member which holds return in bool.
    bool bReturn = false;

    // Assume FnWhichReturnsBOOL is a function
    // which returns BOOL.
    if( FALSE != FnWhichReturnsBOOL())
    {
        // Since its success, set return as true.
        bReturn = true;
    }

    return bReturn;
}

This can be easly re-written as follows

bool Function()
{
    BOOL bReturn = FnWhichReturnsBOOL();
    return bReturn != FALSE;
}


Wanna read more? check out this link in MSDN – http://msdn.microsoft.com/en-us/library/b6801kcy(VS.71).aspx


Targeted Audience – Intermediate.

Format Milliseconds to Human readable Time.

0


For profiling performance we usually use functions such as GetTickCount() etc to get the time in millisecond resolution. Since they are in milliseconds, its a bit difficult for us to interpret, because our real world time is expressed in hours, minutes and seconds. There is a handy function in the shell to convert the time in milliseconds to human readable form.


You can use the function – StrFromTimeInterval() for converting time in milliseconds to human readable form. See the code snippet below.

#include "Shlwapi.h"
...
// Get the time in milli-seconds.
DWORD dwTickCount = GetTickCount();

// Declare the buffer to hold the string.
const int BufferSize = 255;
TCHAR CurrentTime[BufferSize];

// Get formatted time from tickcount.
StrFromTimeInterval( CurrentTime,
                     BufferSize,
                     dwTickCount,
                     3 ); // hr:min:sec


Its very useful while logging performance related data. And to be honest, several years ago I’ve written a utility function in my project to implement the same, without knowing about this function. Indeed, got a hand full of bugs. ;)

BTW, don’t forget to add Shlwapi.lib to the project settings.


Targeted Audience – Beginners.

How to make you application look "Classic" without disabling Windows themes.

0


The first thing that i do when I get a windows machine is to disable its themes(if any) and reset to classic style. May be I still love those golden days of Win 3.1 and Win98.

Like that some products also keep their classic style UI to avoid confusion to the field engineers due to look and feel changes. For that, the windows themes are disabled while deploying the field machines. But you can still make you application look classic without disabling the whole system themes.


You can use the api – SetWindowTheme() for that. Calling that function will null params will reset your window style to classic. See the code snippet below.

#include "uxtheme.h"
...
SetWindowTheme( GetSafeHwnd(), L"", L"" );


This is applicable only for windows version from XP onwards. And don’t forget to add UxTheme.lib to the project settings.


Targeted Audience – Beginners.

How to hook memory allocation failures by malloc()?

1

C have malloc() and C++ have more advanced “new” for allocating memory. One of the advantages of new over malloc is that its tailored to report memory allocation failures where malloc() is not. For instance, in C++ we can set a “Allocation failure handler” function by calling _set_new_handler(). When ever “new” fails to allocate function, this function will be called. Its a nice feature that malloc() don’t have by default.

There are several maintenance projects which are actually done in C but ported to C++. Usually instead of rewriting entire source, the legacy code exists in C itself and new feature additions will be done in C++, since they co-exist with each other. So in the old C code base, the malloc() will be used extensively. So hooking memory failures by malloc() are necessary and how can we do it?


By default malloc() won’t call the New Handler function during memory failure. But you can specify to do so by calling _set_new_mode(). See the sample code snippet below.

#include "new.h"

// Memory Allocation Failure Handler.
int AllocationFailureHandler( size_t )
{
    // Do what ever you wish.
    return 0;
}

// The one and only Main.
void main()
{
    // Set the NewHandler and try "new" allocation failures.
    // The NewHandler will be called.
    _set_new_handler( AllocationFailureHandler);
    char* pAllocatedByNew = new char[1000000000000];

    // Check malloc. By default it won't call
    // newHandler on failure.
    char* pAllocatedByMalloc = (char*)malloc( 1000000000000 );

    // Enable allocation failure reporting for malloc.
    // and try once again. This time, NewHandler is called!
    _set_new_mode( 1 );
    pAllocatedByMalloc = (char*)malloc( 1000000000000 );
}

Now hook the memory allocation failures from you legacy code too… ;)


If you have MFC support, then the NewHandler provided by you will be overridden and that of MFC will handle the allocation failure. So take care…

And _set_new_mode() is not the part of C++ language standard. Its Microsoft specific.


Targeted Audiance – Intermediate.

Permanent Bookmarks in VisualStudio.

2


In visual studio, we usually use bookmarks for traversing. Ctrl+F2 is used to add/remove bookmark and F2 to traverse between bookmarks. But when you close the file, all bookmarks in that file will be gone. I often blamed visual studio for not proving a bookmark window like the breakpoint window, where i can store permanent bookmarks. But recently i understood I’m mistaken…


Indeed, there is a permanent bookmark window. By pressing Alt+F2 you can access it. The bookmarks you add via this will be kept even after closing the IDE. See the screenshot below.

The funniest thing is, Even after working in the Visual studio 6.0 for years, i didn’t noticed this one yet. And when I asked some of my peers about this, they are also seeing this stuff for the first time. :) What about you guys? Come on, post your comments… Just to know, whether something wrong with my eyes. ;)


Targeted Audience – Beginners.

auto_ptr as pass by value to functions – you are going to face a crash.

0


Memory leaks are our nightmare and auto_ptr’s are used for making our life easier which does automatic memory deletion. If a pointer is assigned to an auto_ptr, it will be deleted when the auto_ptr went out of scope. But use this automatic deletion carefully, especially while passing it as function arguments by value. You are going to face a crash!


The problem is “owership”. Every auto_ptr holds an ownership flag. when an auto_ptr is assigned to another auto_ptr, the ownership flag is transfered from first to second. And only the auto_ptr with ownership flag enabled, can delete the resource. This method is used to avoid multiple deletion of the same pointer kept by several auto_ptrs. There will be only one owner auto_ptr at a time.

Now when you pass the auto_ptr by value, actually, you are passing the owner ship to the stack variable of the called function. Now the stack parameter will become the owner of your pointer and when the function returns, the auto_ptr in stack will be destructed and since its the owner, it will delete your passed pointer. When you access you main auto_ptr, then you’ll probably get a crash!!! See the code snippet for an e.g.

// Function which receives auto_ptr as value.
void ToUpper( auto_ptr<CString> pString )
{
    // Shows the messageBox.
    pString->MakeUpper();
}

// The one and only Main.
void main()
{
    // An auto_ptr which holds a CString.
    auto_ptr<CString> pString(
        new CString(_T("Hello AutoPtr")));

    // Make the string upper case by
    // passing it as value.
    ToUpper( pString );

    // At this point, your CString is already
    // been deleted by the stack variable in function.

    // Now change the string to Lower and face the crash!!!
    pString->MakeLower();
}


You can make the situation safe by passing by reference. While doing so, only a reference is passed to the stack variable and hence the ownership remains in you main auto_ptr itself.


Targeted Audience – Intermediate.

Visual Studio Split Windows.

0


During maintenance or refactoring, usually you’ve to compare multiple code blocks of the same source file. So what we usually do? Put two bookmarks at both locations by using Ctrl+F2 and we will switch between the blocks by pressing F2 and compare it. While being in one block, the other block resides in our memory. ;) Do you know that visual studio supports window splitters to make your life easier?


1) Take menu Window->Split
2) now the mouse changes to a 4 way splitter.
3) Just click on the desired dimensions to split the current window.
4) Finally it will look like as follows.

Pretty useful, but commonly ignored, huh? ;)


Targeted Audience – Beginners.

Copy-Paste of source files; Compilation Guard Band's worst enemy.

3


In big projects, sometimes you want to write almost similar classes, which is more or less similar. For instance, assume you have a request base class, and the derived classes should implement some common virtual functions.

Usually one easy method is to copy-paste one of the existing derived class so that by making minor change, we can start the next derived class. While doing so, just remember – you are making one of the dangerous, hard to detect bug. When you try to compile your source, the second derived class you created, will show the error

Go to Top