Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Wednesday, October 15, 2008

use find magic to create etags

To create a TAGS file so that you can work with emacs / vim use the following command

find . -ipath '*.p*' -print | etags -

the above command for example will create etags for all the pl , pm files in the current directory

Saturday, September 27, 2008

Little Sugar:Decreasing capacity in C++

When you use vector,string class in C++, the problem that happens is that the capacity just increases and does not decrease, causing the data structure to hog lot of memory.
For example, say in the vector 10 elements were added , then to the same vector 1000000 elements were added. Then 900000 were deleted. This will not cause the capacity to decrease. This might result in the vector still holding on to a lot of memory.

One way to fix this is the sap trick.

vector < int > elements; // the original vector

vector < int > (elements.begin(), elements.end() ).swap(elements)

Wednesday, August 13, 2008

vector::assign

"assign" is a method in STL for the vector class. When ever you need to erase the contents of the vector and replace it with totally new contents use the assign member function .You should use the operator= then all elements of the right hand side container would be copied to the container on the left hand side.

e.g

v1.assign(v2.begin() + v2.size()/2 , v2.end())

Thursday, June 05, 2008

C++ : std::swap and template specialization

say you want to use the swap method provided in std namespace for your own class . Then instead of using the std::swap option blindly , that would involve making use that your class has at least a copy constructor and that the assignment operator is overridden.

It makes more sense to use template specialization for std::swap

class MyClass {
public:
void Swap(MyClass &) ;
};

namespace std {
template<> swap(MyClass& a, MyClass& b){
a.Swap(b);
}
}

so that way we just tune the default swap to use our class specific Swap and things become fast and simple for us .

Wednesday, June 04, 2008

C++ : std::mem_fun

Say you have a class

class MyClass {
public:
int DoSomething(){
}
};

now say you have

std::vector classes;

you can use something like this

for_each(classes.begin(), classes.end(), &DoSomething);

where DoSomething is

int DoSomething(MyClass& e){
d.DoSomething();
}


to call the member function DoSomething rather than the wrapper function use function calls like these

for_each(classes.begin(), classes.end(), mem_fun_ref(&MyClass::DoSomething));

if the classes vector was defined something like this

vector classes

then you would use something like this

for_each(classes.begin(), classes.end(), mem_fun(&MyClass::DoSomething));

C++ : Template specializations

Assuming you have a piece of code that is templatized and looks like this

template
void prettyPrint(T value, char* buf);

now assume that you are using sprintf for formatting the input .

that being the case you can use template specializations like this :

template<> void prettyPrint(int value, char* buf){
sprintf(buf, "%d", value);
}

template<> void prettyPrint(char value, char* buf){
sprintf(buf, "%c", value);
}

Tuesday, June 03, 2008

C++: copy magic

Say if you have a vector and you want to print it . Then instead of the normal for loop and cout call inside the loop you can do the following :

if you have a vector "v"

copy(v.begin(), v.end(), ostream_iterator(cout, "\n"));

this will print the entire vector .

To generalize this you could use something like this :

template
OutputIterator copy(const Container& c, OutputIterator result){
return std::copy(c.begin(), c.end(), result);
}

Thursday, May 22, 2008

C++ : new operator and operator new

The new operator in C++ is something that cannot be changed . For example
when you use code something like this ,

string *ps = new string("Memory Management");

the new operator is used . Its sole purpose is to allocate memory and initialize it.

The new operator in turn uses the operator new to allocate memory which can be overloaded.

its prototype looks like this :

void * operator new(size_t size);

there is another version of new operator called the placement new , that is used to create objects in pre initialized memory. example usage for it looks like this :

string *ps = new(memory) string("Memory Management");

same is the case for delete operator and operator delete

operator new[] is another type of operator that can be used to allocate new arrays

Monday, May 19, 2008

C++ : Creating Objects

Here are 2 simple rules to allocating and deleting objects.

MyObject * myPointer;

while updating object memory always use code like this:

MyObject::update(){
delete myPointer;
myPointer = NULL;
myPointer = MyObject::CreateNew();
}

while deallocating always use code like this:

MyObject::~MyObject(){
delete myPointer;
myPointer = NULL;
}

Sunday, April 13, 2008

C++ : template specialization

template <>
char* Add<char*>(char* a , char* b){
return strcat(a,b);
}

char * res = Add<char*>("foo","bar");

This code refers to a new type of syntax for templates called template specialization syntax.
Generally when you write code for templates .

you end up using stuff like

template<class>

but say you want the same generic code for many cases . In the above mentioned code for example if the add function used the "+" operator to add two types it would have not worked for char* pointers , because the "+" operator does not work with them .

by using the syntax as mentioned above its possible to tell the compiler that there are exceptions to your generic code and that for special cases these new methods should be called.

C++ : The need for virtual destructors

With the advent of object oriented languages the use of polymophism became very common .
In C++ when you have a derived Class and a base class .

when you have code like this :

class Base {
};

class Derived : public Base{
};

Base * p = new Derived();

delete p;

what's wrong with it .

Since this piece of code is based on polymorphism , the base pointer will refer to an instance of a derived class object .

when delete on the pointer p is called , due to static typing in c++ , destructor of Base is called , instead of Derived . To correct this

virtual ~Base(){
}

should be added . By making the destructor virtual the destructor of the derived class would be called now .

Saturday, April 12, 2008

Refactoring : Self Encapsulate Field

Some times in a code base , especially inside a class , a field is referenced from many places.
Say you decide to move this field to another class .

A clean way of doing this is to first extract a getter method for that field within the same class .
Now with all occurances replaced by the getter method , move this getter method to the new class .
Similarly replace the code where the field is being set by the appropriate setter code and then move the setter code to another class .

Refactroing : Handling Duplicate Code

In legacy code bases we see lot of duplicate code . so how do we handle it ?

I am assuming you are using a tool that supports refactoring . In that case ,

Case 1:

If in a class you have lot of repeated code , use extract method refactoring to move the repeated code into a common method inside the class . Now replace if not automatically all occurance s of the repeated code with the call to the newly created method.

Case 2:

You have 2 sibling classes that have same piece of code .

Use extract method to create method with the same name in the 2 classes . Then use pull up refactoring to pull up the common method now in a super class . If the super class does not exist create it now .

Case 3:

You have 2 sibling classes that have almost the same piece of code , but some different bits here and there .

Use extract method to create method with the same signature in both the classes . Then identify the parts that are different , extract these different parts into methods of their own . Make sure that the names of these different parts is same in both sibling classes.

Now use template method design pattern , to create a common method in a super class of these 2 siblings . Using polymorph ism and inheritance to implement the different methods in the sibling classes.

Tuesday, April 08, 2008

C++: Object slicing and pass by value

In C++ , when a object is passed by value to a function that accepts a parameter then object slicing might happen. Consider the following class

class Base {
public:
virtual const char * toString() throw();

};

class Derived : public Base {
public:
virtual const char* toString() throw();
};

Derived derived;
Base base;

void doSomething(Base base){
....
}

doSomething(base);
doSomething(derived);


now we have 2 classes Base and Derived with a common virtual function that have been overridden in the derived class . We create 2 objects "derived" and "base".

Both of them are passed to the function doSomething . What happens in this case .

In the first case , it works the way its supposed to . In the second case , object slicing takes place and the members that are just of derived class are chopped off and the virtual function of the base class is called.

Monday, April 07, 2008

C++ : pointer to member function

class Foo{
public:
int iVal;
int Bar(int);
};


int Foo::* pm;

is a pointer to a member variable that is an integer.

pm = &Foo::iVal;

is used to initailize a pointer to a member variable

Foo foo;

int i = foo.*pm

is used to retrieve values of the pointer to member variable

int (Foo::*pmf) (int) = &Foo::Bar;

is a pointer to member function that is initialized by the address of member function Bar

C++ : Preventing implicit type conversion

class Foo{
public:

Foo(int n ){
...
}

};

Foo foo(42);
Foo boo = 42;

In the above mentioned snippet , the first constructor is matched and called. In the second case , for the assignment operator since the right hand side is 42 and since we have a constructor that takes integer as an argument . The corresponding constructor is called . This is syntactic sugar that can lead to lots of problems . To prevent something like this .

the explicit keyword should be used in front of constructors .

Wednesday, April 02, 2008

C++: Rethrowing exceptions

Consider the following piece of code

catch (Base& w)
{
...
throw;
}
catch (Base& w)
{
...
throw w;
}

What do you think is the difference between the 2 approaches above .

In the first case , the exception is re thrown . In the second case a copy is made and a new exception is thrown . Also the copy is based on the static type i.e
Base (copy constructor is called )

C++ : Object Copies in C++ are based on Object's Static Type Not Dynamic Type

Consider the following piece of code

class Base { ... };
class Derived: public Base { ... };

void passAndThrowDerived()
{
Derived local;
...
Base& rw = local;

throw rw;

}


In the above mentioned case . When a copy of rw is made while throwing it .
The copy constructor for the type is called . In this case the since rw is a reference to Base there fore the copy constructor of Base is called rather than the
Copy Constructor of Derived class.

C++ : Why are objects thrown as exception always copied

When an exception is thrown , the objects are generally copied. To explain this consider the following :

{
MyObject myObject;
cin >> myObject;
throw myObject;
}

if the object myObject was passed by reference then the same myObject would be thrown out . If the same object is thrown out then as soon as it goes out of scope , its destructor would get called and as a result of which some garbage would finally reach the exceptional handling code .

It is for this reason that copies of myObject are thrown rather than the original one .

Monday, March 24, 2008

Little Sugar : C++

In C++ have you imagined what would happen if the destructor of your class throws an exception . For starters , the object would not get destroyed properly . Actually in reality the control would go back to the callee from the current point directly.

Alright , now think what would happen if the destructor got called as a part of some exception handling code and this destructor threw an exception .

Since the active callee is calling the destructor due to some raised exception .
it would result in the terminate() function getting called and though would terminate the program immediately