vijayan121 1,152 Posting Virtuoso

> the self-assignment test does not work well in class hierarchies either,
> even with use of boost::addressof().

it is unlikely that using value semantics on object-oriented types is something that people would want to do. however, the self-assignment test would work perfectly as long as the overloaded assignment operator is ThreeD& ThreeD::operator= ( const ThreeD& that ) ; that would be a reference to the anonymous base class sub-object (of type ThreeD) and the boost::addressof() would return the address of the ThreeD sub-object.

the 'make temporary copy and swap' technique does not work at all in class hierarchies when the base class ThreeD is abstract.

> difficult to implement an exception-safe assignment operator without creating a
> temporary copy - of either the object itself, or (at a minimum) of the data it contains.
> Doing a self-assignment test - even if it works - does not change that.

not necessarily if the class is designed with exception-safety in mind. for example,

struct A
{
  public:
     // ...
  private: std::list< std::string > strlist ;
};

exception-safe assignment operator can be written without creating a temporary copy of the strings.

vijayan121 1,152 Posting Virtuoso

perhaps the easiest way is to use the iostream formatted output facilities:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

int main()
{
  double a = 2.5632, b = 2.5652 ;

  std::ostringstream strout ;
  strout << std::fixed << std::showpoint << std::setprecision(2)
         << "a: " << a << "  b: " << b << '\n' ;

  std::cout << strout.str() ;
}
vijayan121 1,152 Posting Virtuoso

a little less verbose, and a little more efficient:

#include <vector>
#include <string>

int main ( int argc, char** argv )
{
  std::vector< std::string > arguments( argv, argv+argc ) ;
}
vijayan121 1,152 Posting Virtuoso

>> The above is common practice, but it is easily broken.
>> Imagine, for example, a class that supports its own operator&() ...
>> The most useful way I've found to do an assignment operator is;
>> ...
>> the only cost is associated with creating a temporary copy of *this.

we can get the benefits of the recommended approach without incurring the overhead of creating and destroying a temporary copy

#include <boost/utility.hpp>

ThreeD& ThreeD::operator= ( const ThreeD& that )
{
  if ( this != boost::addressof(that) )
  {
    // assign in an exception-safe manner
  }
  return *this;
}

http://www.boost.org/doc/libs/1_36_0/libs/utility/utility.htm#addressof

vijayan121 1,152 Posting Virtuoso

for the predefined streams, it's safe to mix C stdio and C++ iostreams. you can safely use stdin and std::cin in the same program; the C++ Standard guarantees that it will work the way you would expect it to.

if you don't need to mix C stdio and C++ iostreams on the same stream, you can get better performance by turning this feature off std::ios_base::sync_with_stdio(false); however, if you need to open a file with C++ iostreams, and at the same time access that file as a C FILE*, there's nothing in the C++ standard to support that usage by default. however, the library is extensible, and a std::streambuf derived class that supports this is just a couple of dozen lines of code.

Salem commented: Nice answer. +21
vijayan121 1,152 Posting Virtuoso

> As a destructor releases memory for an object ...
a destructor does not release memory. it deinitializes an object and after it executes, what is left is uninitialized memory (earlier occupied by the object, whose lifetime is now over). how (or if) this memory is released depends on the object's storage duration.
try this out:

#include <iostream>
#include <cstdlib>

struct A
{
  static inline void* operator new( std::size_t sz )
  {
    void* memory = std::malloc(sz) ;
    std::cout << "allocated memory at address " << memory << '\n' ;
    return memory ;
  }
  static inline void operator delete( void* memory )
  {
    std::cout << "release memory at address " << memory << '\n' ;
    std::free( memory ) ;
  }
  A() { std::cout << "construct object at address " << this << '\n' ; }
  ~A() { std::cout << "destroy object at address " << this << '\n' ; }
};

int main()
{
  A* pa = new A ;
  delete pa ;
  std::cout << "--------------\n" ;
  A object ;
}

> However, the program executes smoothly.
memory is not released twice; that does not mean that the program is correct. it results in undefined behaviour.

Once a destructor is invoked for an object, the object no longer exists; the behavior is undefined if the destructor is invoked for an object whose lifetime has ended. [Example: if the destructor for an automatic object is explicitly invoked, and the block is subsequently left in a manner that …

vijayan121 1,152 Posting Virtuoso

> i would like to avoid doing 4 times 2 shift for each char.
> For each char i do 4 shift operations and 4 bitwise AND's, thats 8 bitwise operations.

you can reduce it to just 4 AND operations by using 4 bit masks.

#include <iostream>
#include <limits>

int main()
{
  enum { char_bits = std::numeric_limits<unsigned char>::digits };
  struct _assert { char char_has_8_bits[ char_bits==8 ? +1 : -1 ] ; };

  enum { N = 8 } ;
  unsigned char* chr = new unsigned char[N];
  // initialize array

  const unsigned char mask[] = { 0xc0, 0x30, 0xc, 0x3 };
  for( int i=0 ; i<N ; ++i )
  {
    // unroll a loop here
    std::cout << (chr[i]&mask[0]) << '\n' << (chr[i]&mask[1]) << '\n'
              << (chr[i]&mask[2]) << '\n' << (chr[i]&mask[3]) << '\n' ;
  }
}

in this case, the value of the 2 msbs would be 192/128/64/0, the next two would be 48/32/16/0 and so on.
you can speed it up more by treating sizeof(unsigned long) chars (instead of a single char) as a unit for the mask operation. (in this case you need to take care while allocating the array to get it correctly aligned and the size rounded upwards if required)

vijayan121 1,152 Posting Virtuoso

also have a look at codeville http://codeville.org/
it is one one of the easiest to use.

vijayan121 1,152 Posting Virtuoso

you can answer this yourself if you write a small test program and run it. for example:

#include <iostream>

struct A
{
  A() { std::cout << "A::default constructor\n" ; }
  A( const A& ) { std::cout << "A::copy constructor\n" ; }
  A& operator= ( const A& )
  { std::cout << "A::assignment\n" ; return *this ; }
};

struct B { A a[2] ; };

int main()
{
  B one ;
  std::cout << "-----------\n" ;
  B two(one) ;
  std::cout << "-----------\n" ;
  one = two ;
}
vijayan121 1,152 Posting Virtuoso

> Does it make sense to write a virtual method in the templated base class
> in order to force derived classes to have an appropriate addelement() method?
no. the polymorphism provided by templates is compile-time polymorphism; if you need an addelement() in a class and the class does not provide it, it will be caught at compile-time.

> first method would lead to a maintenance nightmare;
> as more chart types are added, more overloaded addelement() placeholders need to be added
true.

vijayan121 1,152 Posting Virtuoso

measurements for the same snippet (3 each) for the microsoft compilers:

compiler: VC++ 9.0 (Express 2008)
optimizations: /Ox /Ob2 /Oi /Ot /Oy /GT /GL
processor: Intel Pentium M 1.86 GHz

c array: 2.076 seconds
vector: 2.094 seconds
valarray operator* : 6.313 seconds
valarray operator* : 2.048 seconds

c array: 2.076 seconds
vector: 2.095 seconds
valarray operator* : 6.39 seconds
valarray operator* : 2.106 seconds

c array: 2.082 seconds
vector: 2.059 seconds
valarray operator* : 6.314 seconds
valarray operator* : 2.049 seconds

-------------------------------------------

compiler: VC++ 8.0 (Express 2005)
optimizations: /Ox /Ob2 /Oi /Ot /Oy /GT /GL
processor: Intel Pentium M 1.86 GHz

c array: 2.105 seconds
vector: 2.115 seconds
valarray operator* : 4.721 seconds
valarray operator* : 2.026 seconds

c array: 2.166 seconds
vector: 2.116 seconds
valarray operator* : 4.634 seconds
valarray operator* : 2.131 seconds

c array: 2.11 seconds
vector: 2.08 seconds
valarray operator* : 4.874 seconds
valarray operator* : 2.005 seconds

> true optimizing compiler discard all loop body statements in vijayan121's test prog because no effect of these assignments

only if you force it by a compiler switch: eg. /Oa (Assume No Aliasing) on microsoft.
otherwise, it has to admit aliasing as allowed by IS 3.10/15

vijayan121 1,152 Posting Virtuoso

if you absolutely need a base class Chart (with virtual functions), a hack would be to overload the AddElement function.

i would prefer using templates for your containers as suggested by Narue in the other thread. and as for this issue:
> ... generic template<class T> container and have a method addelement(T& elt)
> but the implemebtation of addelement() depends on the element being added
template specialization would address the problem.

#include <stdexcept>

struct DataElement { /* ... */ };
struct AverageElement { /* ... */ };

#ifdef INHERIT

struct Chart // base class
{
  virtual void AddElement( const DataElement& ) = 0 ;
  virtual void AddElement( const AverageElement& ) = 0 ;
  // other (pure) virtual functions
};

struct DataChart : Chart
{
  virtual void AddElement( const DataElement& )
  { /* add DataElement */ }

  virtual void AddElement( const AverageElement& )
  { throw std::logic_error("incorrect element type") ; }
  
  // other overrides etc.
};

struct AveragesChart : Chart
{
  virtual void AddElement( const DataElement& )
  { throw std::logic_error("incorrect element type") ; }

  virtual void AddElement( const AverageElement& )
  { /* add AverageElement */ }
   
  // other overrides etc.
};

#else // GENERIC

template< typename T > struct chart_base
{
  // common stuff goes here
};

template< typename T > struct chart ; // generalization

// specialization
template<> struct chart<DataElement> : chart_base<DataElement> 
{
  void addelement( const DataElement& ) ;
  // other DataChart specific stuff
};

// specialization
template<> struct chart<AverageElement> : chart_base<AverageElement>
{
  void AddElement( const …
vijayan121 1,152 Posting Virtuoso

valarrays were introduced with the idea that it might encourage C++ compiler developers for vector processors to implement them as built-in types (the compiler could emit code to optimize the use of the vector pipeline).
See Bjarne Stroustrup, "The C++ Programming Language: Third Edition",
Chapter 22 Numerics, Section 4 Vector Arithmetic, pages 662-79.

the definition of a vector machine is that it can apply a single operation to a number of elements in parallel. the basic idea on a vector machine is this: apply a single operation to an entire array at a time, then apply the next operation to the entire array, and so on.
The prototypical vector machine is the Cray, which has 3 sets of 64 registers each -- it can be loading one set of 64 registers, applying a single operation to another set of 64, and storing the third set of 64 all at the same time. and has a 32-CPU STREAM bandwidth of 360 GB per second.
valarray fits this pattern perfectly, and with a Cray T90, you could get excellent performance with it.

The basic problem with this design is that it requires a huge bandwidth to memory. A typical modern machine has an extremely fast processor, but main memory is a bottleneck (you use a cache to make up the difference). in this case, optimal usage is almost exactly the opposite -- you want to load a single value, apply all your operations to it, then …

vijayan121 1,152 Posting Virtuoso
Derived d;
Base *p = reinterpret_cast< Base*>(&d);

> I found that this is also legal--

it will compile.
it will work correctly if and only if the anonymous base class sub-object is at an offset of zero in the derived class object.

do not get lulled into a false sense of security. a reinterpret_cast is a C++ cast. but that does not mean that it gives you any additional protection regarding correctness compared to a C style cast, or the union technique that you posted in another thread. for a reinterpret_cast too, you need to know precisely what you are doing. and as a programmer, you have to take responsibility for its correctness.

Alex Edwards commented: My apologies for an ignorant response. +3
vijayan121 1,152 Posting Virtuoso

any 3-combination of the N-set would consist of numbers at 3 different positions in the array; you could choose positions i,j,k out of these three such that i<j<k holds.

so doesn't the problem reduce to generating all unique 3-combinations of an N-set.

several algorithms to do this efficiently exist.
Chase's twiddle or Knuth's (volume4) algorithms come to mind.

additional info: http://www.theory.csc.uvic.ca/~cos/inf/comb/CombinationsInfo.html

vijayan121 1,152 Posting Virtuoso

> Could it be because i am entering the string 'key' with spaces?
yes
> how would i fix it?
use std::getline http://www.cppreference.com/cppstring/getline.html

vijayan121 1,152 Posting Virtuoso

> Is there any real different between using an union between two types and a reinterpret_cast between two types
yes, there are quite a lot of differences.
a union reinterprets the layout of memory (depending on which member is accessed).
a reinterpret_cast is a conversion operator.

the conversions that can be performed using a reinterpret_cast are limited; the permissible ones are specified by the standard.

IS 5.2.10 - Reinterpret cast

-1- The result of the expression reinterpret_cast<T>(v) is the result of converting the expression v to type T.
...
Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
-2- The reinterpret_cast operator shall not cast away constness. ...
-3- The mapping performed by reinterpret_cast is implementation-defined. ...

and then it goes on to list the conversions that can be performed explicitly using reinterpret_cast. for example this is what is specified about pointer to integral and integral to pointer conversions:

-4- A pointer can be explicitly converted to any integral type large enough to hold it. The mapping function is implementation-defined.
[Note: it is intended to be unsurprising to those who know the addressing structure of the underlying machine. ]
-5- A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type …

Alex Edwards commented: Thanks for the elaborate explanation! +3
vijayan121 1,152 Posting Virtuoso

if your idea was to have a code sample which will help you understand how virtual function calls are implemented by the microsoft compiler:

#include <iostream>

#if defined(_MSC_VER) && (_MSC_VER >= 1200) && defined(_M_IX86) 

struct A
{
  // __stdcall, args passed on stack, 'this' is the first arg
  virtual void __stdcall foo( int x ) = 0 ;

  // __fastcall, args passed using registers if possible
  // 'this' is the first arg, passed in ecx
  // x is the second arg, passed in edx
  virtual void __fastcall bar( int x ) = 0 ;

  // default is __thiscall
  // 'this' is the first arg, passed in register ecx
  // other args passed on stack
  virtual void foobar( int x ) = 0 ;
};

int main()
{
  struct A_vtbl 
  {
    // microsoft compilers order the vtbl as per declaration order
    // required for support for COM vtbls 

    void ( __stdcall* pfn_foo )( A* This, int x ) ;
    void ( __fastcall* pfn_bar )( A* This, int x ) ;
    
    // __thiscall: pass first arg in ecx, rest on stack
    void ( __thiscall* pfn_foobar )( A* This, int x ) ;

    // other stuff; 
    // rtti etc.
  };

  struct A_shadow
  {
    A_vtbl* vtbl_pointer ;
  };

  struct derived_class : A
  {
    virtual void __stdcall foo( int x )
    { std::cout << "derived_class::foo( " << x << " )\n" ; }

    virtual void __fastcall bar( int x )
    { std::cout << "derived_class::bar( " << x << " )\n" ; }

    virtual void …
vijayan121 1,152 Posting Virtuoso

see IS 9.4.2/4

"...The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer".

GCC is conforming. static constant member object is 'used' (in main) and, therefore, has to be defined.

the main issue here is that if you take the address, the static object has to retain the same address across all translation units. (required for object identity). AFAIK, VC++ 2005 seems to satisfy this requirement.

stroustrup's FAQ on this: http://www.research.att.com/~bs/bs_faq2.html#in-class

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
Alex Edwards commented: For being the first to recommend this book XP +3
vijayan121 1,152 Posting Virtuoso

> cat my_file.txt | grep ^ | wc -l

vijayan121 1,152 Posting Virtuoso

use sockets (or pipes) to communicate keystrokes from one process to the other.

vijayan121 1,152 Posting Virtuoso

Point B(); is the declaration of a function called 'B' which takes no arguments and returns a Point.
modify to Point B ; and you have the definition of a variable called 'B' which is of type Point (initialized via the default constructor).

vijayan121 1,152 Posting Virtuoso

the typical work around (as exemplified by the standard library containers and function objects) is to have the generic type announce dependent types via suitable typedefs.

#include <vector>
#include <iostream>
#include <typeinfo>

template <class T>
class CObject
{
  public:
    typedef T numeric_type ;
    typedef std::vector<T>* output_type ;

    inline virtual ~CObject () { }
    virtual output_type Output( const std::vector<int>* Input ) = 0 ;
};

template< typename T >
typename T::output_type function( T& object,
                                  const std::vector<int>* input )
{
  typedef typename T::output_type result_type ;
  std::cout << "result type is " << typeid(result_type).name() << '\n' ;
  result_type result = object.Output( input ) ;
  return result ;
}
vijayan121 1,152 Posting Virtuoso

to just draw 52 cards in random order without duplicate draws, just fill an array/vector of size 52 with values [1,52] and do a std::random_shuffle on it.
to make 52 draws, marking/discarding duplicate draws, we can avoid the 52 linear searches:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
  std::srand( std::time(0) ) ;
  enum { NCARDS = 52 } ;
  bool already_drawn[NCARDS] = { false } ;
  for( int n=0 ; n<NCARDS ; ++n )
  {
    int drawn = rand()%NCARDS + 1 ;
    std::cout << n+1 << ". " << drawn << '\n' ;
    if( already_drawn[drawn-1] ) std::cout << "Repeat\n" ;
    else already_drawn[drawn-1] = true ;
  }
}
vijayan121 1,152 Posting Virtuoso

to reproduce the white spaces in the original in the reversed sentence:

#include <string>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <ctype.h>

template< typename REV_CHAR_ITER >
void print_reverse( REV_CHAR_ITER rbeg, REV_CHAR_ITER rend )
{
  REV_CHAR_ITER found = std::find_if( rbeg, rend, ::isspace ) ;
  std::copy( found.base(), rbeg.base(),
             std::ostream_iterator<char>(std::cout) ) ;

  if( found != rend )
  {
    std::cout << *found ;
    print_reverse( ++found, rend ) ;
  }
}

int main()
{
  const std::string sentence = "test sentence, containing "
                               "a few  extra     spaces,\t\ttabs" ;
  print_reverse( sentence.rbegin(), sentence.rend() ) ;
  std::cout << '\n' << sentence << '\n' ;
}
Agni commented: as usual, perfect solution... thanks a lot +1
vijayan121 1,152 Posting Virtuoso

the error is this: error C2993: 'float' : illegal type for non-type template parameter 'zero'
non-type template parameters are restricted to
a. constant integral values (including enumerations)
b. pointers or references to objects with external linkage.

the simplest work around is: take the parameter as an argument to the constructor.

template < typename DataType, int size >
class Array
{
  public:
    explicit Array( const DataType& z = DataType() ) : zero(z) {}
    // ...
    // ...
  private:
    DataType m_array[size];
    DataType zero ;
};

int main ()
{
  Array<int, 5> iarray5(42);
  Array<int, 10> iarray10(30);
  Array<float, 5> farray15(0.0f);
}
vijayan121 1,152 Posting Virtuoso

> Windows heap is not the same thing as CRT heap

and to complicate matters, there may be several win32 heaps (and several CRT heaps) in a process.
if an exe or shared object (DLL) is linked with the static C/C++ runtime library, then the module has its own private copy of the C/C++ runtime (and its own private CRT heap).
even if you link all modules with the DLL version of the C/C++ runtime library, there may not be an agreement across modules on which version of the C/C++ runtime (MSVCRT??.DLL) to use. GetProcessHeaps retrieves handles to all of the heaps that are there in the process. and you would have to do a HeapWalk (win32) / _heapwalk (CRT) on each of them.

vijayan121 1,152 Posting Virtuoso

simulating long division by hand (shift and subtract):
http://courses.cs.vt.edu/~cs1104/Division/ShiftSubtract/Shift.Subtract.html

vijayan121 1,152 Posting Virtuoso

having re-read the thread, i realize that my earlier post was asinine.
perhaps you should consider using a programming language that is not statically typed (ideally with some support for reflective programming).

vijayan121 1,152 Posting Virtuoso

you can get the effect that you intended (specializing the nested class without also specializing the containing class) this way: delegate the nested template to another template at some namespace scope which has an explicit specialization:

#include <iostream>

namespace A
{
  namespace impl_detail
  {
    // generalization:
    template < typename T, typename X > struct B_G
    {
      static inline const char* id() { return "generalization" ; }
    } ;

    // specialization:
    template < typename T > struct B_G< T, int >
    {
      static const char* id() { return "specialization (int)" ; }
    } ;
  }

  template <typename T>
  struct B
  {
    template <typename X> struct G : impl_detail::B_G<T,X> {} ;
  };
}

int main()
{
  std::cout << A::B<double>::G<void>::id() << '\n' ;
  std::cout << A::B<void>::G<double>::id() << '\n' ;
  std::cout << A::B<double>::G<int>::id() << '\n' ;
  std::cout << A::B<void>::G<int>::id() << '\n' ;
}

as Narue mentioned, it is a gray area, and has been the subject of debate since 1988.
this issue is still not closed and is part of the C++ Standard Core Language Defect Reports (under consideration by the working group).
http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#44

vijayan121 1,152 Posting Virtuoso

http://www.cppreference.com/cppstack/index.html

#include <stack>

struct mystruct { /* whatever */ } ;

int main()
{
  std::stack<int> int_stack ;
  std::stack<mystruct> stack_of_mystruct ;
  int_stack.push(100) ;
  // etc.
}
vijayan121 1,152 Posting Virtuoso

> The structs are padded so that no padding occurs when we create an array of them,
> like with a scalar variable because if the compiler padded the struct when it created the
> array it wouldn't be the same behaviour we have when we created an array of integers.
> Is this notion correct?

not merely 'it wouldn't be the same behaviour we have when we created an array of integers'. array subscript and pointer arithmetic would not work otherwise.

> an anyone put it more formally?

the formal exposition is in the legalese in the IS (ISO/IEC 14882).
but this arises out of a few simple requirements:
1. the layout and sizeof an object of a particular compile-time type should be known at compile-time.
2. these have to be independent of the storage duration of the object.
3. these also have to be independent of whether the object is an element of an array, a member of a class, a base class sub-object etc.
4. object types can have alignment requirements.
5. an object should be allocated at an address that meets the alignment requirements of its object type.
6. array subscript and pointer arithmetic should work correctly.
7. the memory model of C++ should be compatible with that of C89.

here is a (poor) attempt at a formal explanation:

struct A
{
   char a ;
   int b ;
   char c …
vijayan121 1,152 Posting Virtuoso
struct align1
{
	double a;
	char b;
	int c;
	short d;
};

> why the compiler pads the structure in the end?

hint:
1. does the struct align1 have an alignment requirement?
2. if we create an array align1 array[5] ; would the alignment be right for every element in the array?

vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <limits>

// addition can be done using bitwise xor
// with adjustments for carry bits
unsigned int plus( unsigned int first, unsigned int second )
{
  unsigned int carry = first & second ; // the carry bits
  unsigned int result = first ^ second ; // the result bits

  while( carry ) // loop over the carry bits
  {
    carry <<= 1U ; // shift carry to next bit
    unsigned int temp = result ^ carry ;
    carry &= result ;
    result = temp ;
  }

  return result;
}

// to subtract, add the two's complement
unsigned int minus( unsigned int first, unsigned int second )
{
  unsigned int carry = ~second & 1U ;
  unsigned int twos_complement = ~second ^ 1U ;

  while( carry )
  {
    carry <<= 1U ;
    unsigned int temp = twos_complement ^ carry ;
    carry &= twos_complement ;
    twos_complement = temp;
  }

  return plus( first, twos_complement ) ;
}

int main()
{
  enum { RADIX = std::numeric_limits<unsigned int>::radix } ;
  struct check_it { char static_assert[ RADIX == 2 ? 1 : -1 ] ; } ;

  for( int i=0 ; i<10 ; ++i )
  {
    unsigned int a = std::rand()%1000 ;
    // a*7 === ( a*8 - a ) === ( a*4 + a*2 + a )
    std::cout << a << " * 7  = " << minus( a<<3U, a ) << " ("
       << plus( a<<2U, plus( a<<1U, a ) ) << ") (" << a*7 << ")\n" ;
  }
}
Alex Edwards commented: You've got quite a head on your shoulders =P +1
vijayan121 1,152 Posting Virtuoso

in general prefer catching exceptions by reference rather than by value.
if the actual object thrown is of a derived class, catching by reference avoids slicing (virtual functions will behave polymorphicaly, the class can be abstract). it also has the minor performance advantage of avoiding the making of a copy of the object. and to be const-correct, unless your intent is to modify the exception object, catch by const reference.

class MyException
{
	public:
    // ...
		string getMsg(void) const ;
    // ...

};
 
// ...
 
string MyException::getMsg() const { return msg; }
 
// ... 

//======this is main function 1=======
    // ...
		catch( const MyException &e )
		{
			cout << e.getMsg() << endl ;
		}

also see:
More Effective C++: 35 More Ways to Improve Your Programs and Designs by Scott Meyers -
ITEM 13. Catch Exceptions by Reference.
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.7

vijayan121 1,152 Posting Virtuoso

> ...threw that one out of my backside as a "guess" to see if it was remotely close,...
yes, that was apparent from your post.
i was alarmed when the original poster responded with:

i have to use this into my projects, i m working on. this will/should help our developers.

vijayan121 1,152 Posting Virtuoso

yes, you can compute the sum and product in one go.
however, floating point arithmetic would not give correct results.
you would need to use a big integer type.

vijayan121 1,152 Posting Virtuoso

if the pattern matching is done on a very long sequence of characters (eg. searching for the occurrence of a particular phrase or word in a large book), there are several interesting algorithms. here is a link that explores some of them. http://www.jea.acm.org/ARTICLES/Vol4Nbr2/index.html

vijayan121 1,152 Posting Virtuoso

this makes only one pass through the array (breaking when the duplicate is found).
however, the requirement 'You can access each array member only once' is violated.
also, it modifies the array as it goes along; perhaps even this is not allowed.

int duplicate_number( int* array, std::size_t N )
{
  for ( std::size_t i = 0 ; i<N ; ++i )
  {
    int number = array[i] > 0 ? array[i] : -array[i] ;
    number = number -1 ; // [1,N] => [0,N-1] 
    
    // use negative value to mark the number 
    if( array[number] > 0 ) array[number] = -array[number] ;
    else return number+1 ; // already marked earlier; duplicate
  }
}
vijayan121 1,152 Posting Virtuoso

> The address of a constructor shall not be taken.
> - I am not getting it.

perhaps this snippet will explain this (and a few other things about constructors):

namespace A
{
  enum COLOUR {} ;
  void foo( COLOUR ) {}
  struct bar { bar( COLOUR ) {} void function( COLOUR ) {} };
}

void fun1( A::COLOUR clr )
{ foo(clr) ; } // ok, function A::foo found via koenig lookup

void fun2( A::COLOUR clr )
{ bar(clr) ; } // error, A::bar found, but it is not a function

int main()
{
  A::COLOUR clr ;
  A::bar object( clr ) ;

  object.function( clr ) ; // ok, call function
  object.A::bar::function( clr ) ; // ok, call function

  object.bar( clr ) ; // error, invalid use of struct A::bar
  object.A::bar::bar( clr ) ; // error, invalid use of struct A::bar

  // ok, pointer to member function A::bar::function
  bool not_null = &A::bar::function ;

  // error, &A::bar::bar is not a legal expression
  // address of a constructor cannot be taken
  not_null = &A::bar::bar ;
}

> What is a leak? How is it caused by that code?
a leak is unintentional resource consumption by a program because the program fails to release resources when they are no longer needed. the most often talked about kind of leak is a memory leak; caused by an error in a program that prevents it from freeing up (dynamically allocated) memory that it no longer can use. Foo foo = (*(new …

Prabakar commented: Thanks:) +1
vijayan121 1,152 Posting Virtuoso

consider using a textual format (maybe xml).

text is a universal format; it is easy for people to read, write, and edit.
and the network payload is easier to inspect, to modify and to debug.

text data is transparent and help enforce encapsulation between programs.

a textual protocol tends to future-proof your system. one reason is that ranges on numeric fields, padding of members and endianness aren't implied by the format itself. on the other hand, binary formats are platform specific and are difficult to extend.

vijayan121 1,152 Posting Virtuoso

@Prabakar

> Can a constuctor return a object?
> Foo Foo::SubFoo() const { return ::SubFoo() ; } > Could you please explain me how the code calls SubFoo constructor. ::subFoo() as an expression is evaluated to be an anonymous object of type ::SubFoo > My guess:
> calling an object's constructor will create a temp object

well, an an object's constructor cannot really be called

Constructors do not have names. ...
...
A constructor is used to initialize objects of its class type. Because constructors do not have names, they are never found during name lookup; however an explicit type conversion using the functional notation will cause a constructor to be called to initialize an object. ...
...
A functional notation type conversion can be used to create new objects of its type. [Note: The syntax looks like an explicit call of the constructor. ] ...

ISO/IEC 14882(E) (12.1 - 1, 2, 13 )

> which will be destroyed immediately

after the initialization of the return value.

There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. The first context is when an expression appears as an initializer for a declarator defining an object. In that context, the temporary that holds the result of the expression shall persist until the object's initialization is complete. ...

- ISO/IEC 14882(E) 12.2 -4-
and a good compiler would use RV optimization to avoid …

vijayan121 1,152 Posting Virtuoso

you could do it this way.

#include <iostream>

struct SubFoo ;

struct Foo
{
   Foo SubFoo() const ;
};

struct SubFoo : Foo
{
  SubFoo() { std::cout << "SubFoo constructor\n" ; }
} ;

Foo Foo::SubFoo() const { return ::SubFoo() ; }

int main()
{
  Foo foo = Foo().SubFoo();
}

but don't. it creates one of the worst kinds of cyclic dependencies- between a base class and a derived class.

vijayan121 1,152 Posting Virtuoso

> i need ti update x,y and z values for all the objects simultaneously...not one by one...
if you need to share members for some (not all) objects (perhaps for some period of time), consider using std::tr1::shared_ptr or boost::shared_ptr to hold the members. http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/shared_ptr.htm shared pointers will also allow sharing of members across objects belonging to different classes.

vijayan121 1,152 Posting Virtuoso

a cv-qualifier suffix following the (non-static) member function's parameter list is a specifier for the this pointer which is an implicit parameter to the function. overloading on cv-qualifiers is overloading on the type of the this pointer; and normal overloading resolution applies. eg.

#include <iostream>
#include <typeinfo>

struct some_class
{
  void foo( int a )
  { std::cout << "type of this: " << typeid(this).name() << '\n' ; }
  void foo( int a ) const
  { std::cout << "type of this: " << typeid(this).name() << '\n' ; }
  void foo( int a ) volatile // esoteric
  { std::cout << "type of this: " << typeid(this).name() << '\n' ; }
};

int main()
{
  some_class a ;
  const some_class& ca = a ;
  volatile some_class& va = a ;

  a.foo(100) ;
  ca.foo(100) ;
  va.foo(100) ;
}

overloading on the const specifier is done for reasons of const-correctness. for example, begin() is overloaded on the const specifier by standard containers.
see: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.12

vijayan121 1,152 Posting Virtuoso

IPv4: man gethostbyname http://www.freebsd.org/cgi/man.cgi?query=gethostbyname&sektion=3&apropos=0&manpath=FreeBSD+7.0-stable

IPv6 and other address families: gethostbyname2 getaddrinfo http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&sektion=3&apropos=0&manpath=FreeBSD+7.0-stable

// IPv4 address lookup
#include <netdb.h>
#include <arpa/inet.h>
#include <iostream>

int main()
{
  const char* const host = "www.toolbar.google.com" ;
  const hostent* host_info = 0 ;

  for( int attempt=0 ; (host_info==0) && (attempt<3) ; ++attempt )
    host_info = gethostbyname(host) ;

  if(host_info)
  {
    std::cout << "host: " << host_info->h_name << '\n' ;

    for( int i=0 ; host_info->h_aliases[i] ; ++i )
      std::cout << " aka: " << host_info->h_aliases[i] << '\n' ;

    for( int i=0 ; host_info->h_addr_list[i] ; ++i )
    {
      const in_addr* address = (in_addr*)host_info->h_addr_list[i] ;
      std::cout << " address: " << inet_ntoa( *address ) << '\n' ;
    }
  }
  else herror( "error" ) ;
}
vijayan121 1,152 Posting Virtuoso

Write a trivial program that calls GetEnvironmentStringsW, and step into it in the debugger’s assembly window mode. You’ll see code that looks like this:

mov  eax,fs:[0x18]              
  mov  eax,dword ptr [eax+0x30]   
  mov  eax,dword ptr [eax+0x10]   
  mov  eax,dword ptr [eax+0x48]   
  ret

It’s relatively well known (including info from the Platform SDK’s WINTERNL.H file) that FS:[0x18] points to a thread’s Thread Environment Block (or TEB). Offset 0x30 within the TEB points to the Process Environment Block (or PEB.).

Knowing that the first two instructions of GetEnvironmentStringW put the address of the PEB into EAX, what can we infer? The third instruction grabs a DWORD value from offset 0x10 in the PEB. It must be a pointer to a structure of some kind because the fourth instruction dereferences that value (+ 0x48). ...

from Matt Pietrek's blog entry on which the (32 bit) code is `based

obviously, this is 32-bit code (and the PEB referred to is the PEB for 32-bit) and will not work on a 64-bit implementation. but you could use a similar technique to figure out what the offsets are for 64-bit XP.

vijayan121 1,152 Posting Virtuoso

n is made automatically from n.o by running the linker (usually called ld) via the C compiler. The precise command used is ...

This rule does the right thing for a simple program with only one source file. It will also do the right thing if there are multiple object files (presumably coming from various other source files), one of which has a name matching that of the executable file....

In more complicated cases, such as when there is no object file whose name derives from the executable file name, you must write an explicit command for linking.

from http://www.gnu.org/software/make/manual/make.html#Implicit-Rules