Showing posts with label CPP Concepts. Show all posts
Showing posts with label CPP Concepts. Show all posts

Thursday, 23 May 2013

Challenging bug in cpp program - Implementing userdefined string class


#include<iostream>
#include<cstring>
#include<new>
using namespace std;
class string_class
{
char *p;
int len;
public:


========== Empty Constructor ==========

string_class()
{
cout<<"000000000000000000000000000000000\n";
}

========== Single Parameterised Constructor ==========
string_class(const char *str)
{

cout<<"see..in single constructor arg char*...\n";
len=strlen(str);
p=new char[len+1];
strcpy(p,str);
cout<<"see.....\n";
}
string_class(const string_class& str1,const string_class& str2)
{

cout<<"string_class(const string_class& str1,const string_class& str2)"<<"\n";
int len1,len2;
len1=strlen(str1.p);
cout<<"in str1 str2="<<'\n';

len2=strlen(str2.p);
cout<<"len1,len2 is "<<len1<<" "<<len2<<"\n";
cout<<str1.p<<" "<<str2.p<<"\n";
cout<<len1+len2+1<<"\n";
//delete p;
len=len1+len2;
//delete p;
p=(char*)new char[(len+1)];
cout<<"success"<<'\n';
cout<<len1+len2+1<<'\n';
strcpy(p,str1.p);
cout<<p<<"kkk"<<'\n';
strcpy((p+len1),str2.p);
//p9[len1+len2]='\0';
cout<<p<<'\n';
}
==================================================
string_class(const string_class& str1,const char *str2)
{
cout<<"string_class(const string_class& str1,const char *str2)"<<"\n";
int len1,len2;
len1=strlen(str1.p);
len2=strlen(str2);
//delete p;
p=new char[len1+len2+1];

strcpy(p,str1.p);
strcpy((p+len1),str2);
}
==================================================
string_class(const char *str1,const string_class& str2)
{
cout<<"string_class(const char *str1,const string_class& str2)"<<"\n";
int len1,len2;
len1=strlen(str1);
len2=strlen(str2.p);
cout<<"in str1 str2="<<len1<<len2<<"\n";
//delete p;
p=new char[len1+len2+1];
strcpy(p,str1);
strcpy((p+len1),str2.p);
}
==================================================
string_class(const string_class& str1, char ch2)
{
cout<<"string_class(const string_class& str1,const char ch2)"<<'\n';

int len1;
len1=strlen(str1.p);
cout<<"in str1, ch2="<<len1<<"\n";
//delete p;
p=new char[len1+2];
strcpy(p,str1.p);

strcpy((p+len1),&ch2);

p[len1+1]='\0';
cout<<p<<'\n';
}
==================================================
string_class(char ch1,const string_class& str2)
{
cout<<"string_class(const char ch1,const string_class& str2)"<<"\n";
int len2;
len2=strlen(str2.p);
cout<<"in ch1 str2="<<len2<<"\n";
//delete p;
p=new char[len2+2];
strcpy(p,&ch1);
cout<<p<<'\n';
strcpy((p+1),str2.p);
}
==================================================
friend ostream& operator<<(ostream& os, const string_class& str)/////////////////////for object overload cout//////////global friend function///////////
{
os << str.p ;
return os;
}
friend istream& operator>>(istream& os,const string_class& str)/////////////////////for object overload cout//////////global friend function///////////
{os>> str.p;
return os;
}
friend void swaap(string_class& str1,string_class& str2)
{
string_class str3;
str3=str1;
str1=str2;
str2=str3;
}
friend string_class operator+(const string_class& str1,const string_class& str2)
{
cout<<" friend string_class operator+(const string_class& str1, const string_class& str2)"<<'\n';
string_class temp0(str1,str2);
return temp0;
}

==================================================

friend string_class operator+ (const char *str1, const string_class& str2)
{
cout<<"friend string_class operator+ (const char *str1, const string_class& str2)"<<"\n";
string_class temp1(str1,str2);
return temp1;
}
==================================================

friend string_class operator+ (const string_class& str1, const char *str2)
{

cout<<"friend string_class operator+ (const string_class& str1, const char *str2)"<<"\n";
string_class temp2(str1,str2);
cout<<"in str1,str2 funct\n";
return temp2;
}


==================================================
friend string_class operator+ (char ch1, const string_class& str2)
{
cout<<"friend string_class operator+ (const char ch1, const string_class& str2)"<<"\n";
string_class temp3(ch1,str2);
return temp3;
}

==================================================

friend string_class operator+ (const string_class& str1,char ch2)
{
cout<<"friend string_class operator+ (const string_class& str1,const char ch2)"<<"\n";
string_class temp4(str1,ch2);
cout<<"in str1,ch2 funct\n";
return temp4;
}



};

==================================================

main()
{
cout<<"main\n";


string_class str2("shiva");
string_class str4("kumaraswamy ");
string_class str1("ganapathi");
string_class str3,str5;
str3=str2+'U'+str4;
str5=str4;
//ganapathiTshiva
cout<<"in main......................."<<str3;

}

Implementing userdefined string class

Not working in case of str3=str4+'U'+str2;
Getting segmentation fault. Try It Out!


Friday, 11 May 2012

Reference Counting


The principle of entropy applies to software just as well as it does to the physical world—all entities tend to disintegrate over time. An IT software project may begin with a short scale prototype of easier implementation and clear design. Those select few prototypes that make it to the marketplace will often undergo rapid expansion. This is usually in response to an avalanche of customer requests for additional (and sometimes esoteric) new features, as well as defects. New development combined with bug fixes tend to wreak havoc on the original crystal-clear design. Over time, the clarity of the design and implementation evaporates through maintenance and frequent release cycles. Software inevitably tends towards chaos. The only factor separating the good ones from the not-so-good ones is the rate of decay.


Standard Template Library


The Standard Template Library (STL) is a powerful combination of containers and generic algorithms. From a performance perspective, a few questions immediately come to mind:

The STL comes bundled with performance guarantees of the asymptotic complexity of the various containers and algorithms. What does it really mean?

The STL consists of many containers. Faced with a given computational task, what containers should I use? Are some better than others for a given scenario?

How good is the performance of the STL? Can I do better by rolling my own home-grown containers and algorithms?

We will address these and other related issues in this chapter.

Even though we often refer to "the STL performance," it should be noted that the STL has various distinct implementations with varying degrees of performance. The measurements provided in this chapter are a reflection of one popular implementation. The observations we make, however, should apply to STL implementations in general.


Inlining Basics

There are a number of "tricks" that can make inlining more effective. This chapter is dedicated to these tricks. These mechanisms are increasingly available as compiler options and optimizations. Check to see what your compiler will do for you before investing any significant effort in doing them yourself.

Single-Threaded Memory Pooling


Frequent memory allocation and deallocation can play a significant role in degrading application performance. The performance degradation stems from the fact that the default memory manager is, by nature, general purpose. An application may use memory in a very specific way and pay a performance penalty for functionality it does not need. You could counter that by developing specialized memory managers. The design space for special-purpose memory managers is multidimensional. At least two dimensions easily come to mind: size and concurrency. The size dimension has two distinct points:

Fixed-size Memory managers that allocate memory blocks of a single fixed size.

Variable-size Memory managers that allocate memory blocks of any size. Request size is not known in advance.

Similarly, the concurrent dimension has two points as well:

Single-threaded The memory manager is confined to a single thread. The memory is used by a single thread and does not cross thread boundary. This class is not concerned with multiple threads stepping on one another.

Multithreaded This memory manager is used by multiple threads concurrently. The implementation will have code fragments whose exceution is mutually exclusive. Only one thread can execute in any of these fragments at any point in time.

Right now we already have four distinct flavors of specialized managers: those corresponding to the product of the size dimension, {fixed, variable}, with the concurrent dimension, {single-threaded, multithreaded}. In this chapter we will examine the single-threaded dimension of special-purpose managers and their performance implications. Our goal, of course, is to develop alternative memory managers that are much faster than the default one. At the same time, we don't want to develop too many specialized managers. The ultimate goal is to combine speed with as much flexibility and code reuse as we can.



The Return Value Optimization


Anytime you can skip the creation and destruction of an object, you are looking at a performance gain. In this chapter we will discuss an optimization often performed by compilers to speed up your source code by transforming it and eliminating object creation. This optimization is referred to as the Return Value Optimization (RVO). Prior to delving into the RVO we need to understand how return-by-value works.

Virtual Functions


The evolution of programming languages tended to make the programming task easier by shifting some burden from the programmer to the compiler, interpreter, assembler, or linker. Programs are becoming easier to develop, maintain, and extend. The problem with this progress is that it is often a zero-sum game where gains in one area mean losses in another. In particular, advances in programming often translate into loss of raw speed. Dynamic binding of function calls is one among many contributions C++ has made to C programming. It shifts the burden of type resolution from the programmer to the compiler, which is good. On the other hand, it can have a negative impact on cost, which is what we intend to examine.


Catching an Exception

Catching an Exception

We catch exception objects by their type using one or a series of catch clauses. A catch clause consists of three parts: the keyword catch, the declaration of a single type or single object within parentheses, and a set of statements within curly braces that does the actual handling of the exception. For example, consider the following set of catch clauses:
// defined elsewhere ... 
extern void log_message( const char* ); 
extern string err_messages[]; 
exterm ostream log_file; 


bool some_function() 
{ 
    bool status = true; 


    // ... we'll get to this part! 


    catch( int errno ){ 
        log_message( err_messages[ errno] ); 
        status = false; 
    } 
    catch( const char *str ){ 
        log_message( str ); 
        status = false; 
    } 
    catch( iterator_overflow &iof ){ 
        iof.what_happened( log_file ); 
        status = false; 
    } 


    // last line of function 
    return status; 
} 
The following catch clauses handle the three exception objects we threw in the preceding section:
throw 42;
throw "panic: no buffer!";
throw iterator_overflow( _index, Triangular::_max_elems );
The type of the exception object is compared against the exception declaration of each catch clause in turn. If the types match, the body of the catch clause is executed. For example, when we throw our iterator_overflow object, the three catch clauses are examined in turn. The exception declaration of the third clause matches the type of the exception object, and the associated statements are executed. The what_happened() member function of our exception class is invoked through iof, the exception object. The const char* return value is passed to some external log_message() function. Following that, status is set to false.
This represents a complete handling of the exception. Normal program execution resumes at the first program statement following the set of catch clauses. In our example, normal program execution begins again with the return of status.
What happens with the throw of the string literal? The matching catch clause this time is the second instance. log_message() is invoked with the str exception object as its argument. status is set to false. Again, the exception is now handled. Control flows past the third catch clause, and normal program execution begins again with the return of status.
It may be that we cannot completely handle an exception. After having logged the message, we might need to rethrow the exception for further handling elsewhere in another catch clause:
catch( iterator_overflow &iof )
    { 
        log_message( iof.what_happened() ); 


        // rethrow for another catch clause to handle 
        throw; 
    } 
A rethrow expression consists only of the throw keyword. It can occur only within a catch clause. It rethrows the exception object, and the search for a matching catch clause continues.
A catch-all handler allows us to match every exception type. In place of the exception declaration, we specify an ellipsis. For example,
// matches all exceptions 
catch( ... ) 
{ 
    log_message( "exception of unknown type" ); 
    // clean up and exit ... 
} 

Object-Based Programming


Although we've yet to write a class of our own, we've used classes extensively since Chapter 1: the string and vector classes, the iostream classes supporting input and output, and so on. In this chapter, we design and implement our own classes.

What do we know about classes from our use of them? Before we can use a class, we must make it known to the program because the class is not built into the language. Usually, we do this by including a header file:

#include <string> 
string pooh[ 4 ] = 
    { "winnie", "robin", "eeyore", "piglet" }; 


The class name serves as a type name in the same way as the built-in type names such as int and double. Often, there are multiple ways to initialize an object of a class:

#include <vector> 


string dummy( "dummy" ); 
vector< string > svec1( 4 ); 
vector< string > svec2( 4, dummy ); 
vector< string > svec3( pooh, pooh+4 ); 


Each class provides a set of operations we can apply to objects of the class. These operations typically consist of named functions, such as size() and empty(), and overloaded instances of the predefined operators, such as inequality and assignment:

if ( svec2 != svec3 && ! svec3.empty() ) 
     svec2 = svec3; 


if ( svec2.size() == 4 ) 
     // all is well ... 

What we don't know, generally, is how the class is implemented. Does the string class calculate its size at each request, or does it store the size within each class object? Are the elements of the vector stored within the vector object, or are the elements stored elsewhere and addressed within the vector object by a pointer?

In general, a class consists of two parts: a public set of operations and operators, and a private implementation. These operations and operators are called class member functions and represent the public interface of the class. As users of a class, we can access only the public interface. This, in fact, is how we have used the string class, the vector class, and so on. For example, all we know about the size() member function of string is its prototype: It has a void parameter list and returns an integer value.

The private implementation of a class consists of the member function definitions and any data associated with the class. For example, if the string class object calculates the length of its string with each invocation of size(), no associated data is required and the definition of size() is likely to involve a for loop walking the length of the string. If the string class object stores the length of its string, a private data member must be defined within each class object. This definition of size() returns the value of that member. Each time the length of the string is modified, the data member must be updated.

These kinds of implementation details are usually of no concern to the user of the class. As users, we simply program to the public interface. In this way, as long as the interface does not change, our code using that interface also does not need to change, even if the underlying implementation is reengineered.

In this chapter, we turn from just using classes to providing classes for ourselves and others to use. Designing and implementing classes are the primary activities of C++ programmers.


Generic Programming


The Standard Template Library (STL) consists of two primary components: a set of container classes, including the vector, list, set, and map classes, and a set of generic algorithms to operate over these containers, including find(), sort(), replace(), and merge().

The vector and list container classes represent sequential containers. A sequential container maintains a first element, a second element, and so on through a last element. We primarily iterate over a sequential container. The map and set classes represent associative containers. An associative container supports fast lookup of a value.

A map is a key/value pair: The key is used for lookup, and the value represents the data we store and retrieve. A telephone directory, for example, is easily represented by a map. The key is the individual's name. The value is the associated phone number.

A set contains only key values. We query it as to whether a value is present. For example, if we were to build an index of words that occur in news stories, we would want to exclude neutral words such as the, an, but, and so on. Before a word is entered into the index, we query an excluded_word set. If the word is present, we discard it; otherwise, we include the word in our index.

The generic algorithms provide a large number of operations that can be applied both to the container classes and to the built-in array. The algorithms are called generic because they are independent of both the type of element they are operating on (for example, whether it is an int, double, or string) and the type of container within which the elements are held (whether it is a vector, list, or built-in array).

The generic algorithms achieve type independence by being implemented as function templates. They achieve container independence by not operating directly on the container. Rather, they are passed an iterator pair (first,last), marking the range of elements over which to iterate. While first is unequal to last, the algorithm operates on the element addressed by first, increments first to address the next element, and then recompares first and last for equality. A good first question is, what is an iterator? The next two sections try to answer that.


Procedural Programming



Writing an entire program in main(), as we did in Chapter 1, is not very practical except for small programs written by a single individual. Typically, we factor common operations, such as calculating the elements of the Fibonacci sequence or generating a random number, into independent functions. This approach has three primary benefits. First, our programs are simpler to understand because they are a sequence of function calls rather than the code sequence to accomplish each operation. Second, we can use the functions across multiple programs. Third, it is easier to distribute the work across multiple programmers or groups within a project.

This chapter covers the basic rules for writing independent functions. It also briefly discusses overloaded and template functions and illustrates the use of pointers to functions.



Basic C++ Programming


we evolve a small program to exercise the fundamental components of the C++ language. These components consist of the following:
A small set of data types: Boolean, character, integer, and floating point.
A set of arithmetic, relational, and logical operators to manipulate these types. These include not only the usual suspects, such as addition, equality, less than, and assignment, but also the less conventional increment, conditional, and compound assignment operators.
A set of conditional branch and looping statements, such as the if statement and while loop, to alter the control flow of our program.
A small number of compound types, such as a pointer and an array. These allow us, respectively, to refer indirectly to an existing object and to define a collection of elements of a single type.
A standard library of common programming abstractions, such as a string and a vector.


Throwing an Exception

The exception handling facility consists of two primary components: the recognition and raising of an exception and the eventual handling of the exception. Typically, an exception is raised and handled within various member or nonmember functions. After an exception is raised, normal program execution is suspended. The exception handling facility searches for a portion of the program that is capable of handling the raised exception. After the exception has been handled, program execution resumes in the portion of the program that has handled the exception.
In C++, we raise an exception by using the throw expression:
inline void Triangular_iterator::