DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
No More Array Errors (Part I) - Block(3C++)

Other Bells and Whistles

Another way that Blocks differ from arrays is that Blocks can be assigned.

       int a1[10], a2[10];
   

a1 = a2; Compiler error

Block<int> b1(20), b2(10);

b1 = b2; OK

Assignment entails reallocation. The effect of the above assignment is to (1) free all of b1's cells, (2) allocate the same number of cells in b1 as in b2, and (3) copy the elements of b2 into the cells of b1.

To be absolutely certain that step (2) succeeded, you could do this:

       b1 = b2;
       if(b1.size()==0)error();

Another Block feature lacking in arrays is the ability to (1) pass Blocks by value, and (2) return them as function results:

       //  You can't do this:
   

int[] foo( int a[] ){ ... return a; }

// But you CAN do this:

Block<int> foo( Block<int> b ){ ... return b; }

You can do both things with Blocks because Blocks have a copy constructor; the copy constructor is invoked implicitly whenever a Block is passed by value or returned as a function result. It is also invoked when a Block is initialized with the contents of another Block.

As with assignment, the copy constructor entails reallocation, so failure is possible. To be absolutely certain that allocation succeeded, check the result using size(). Since there are two places where failure can occur, we perform the check in two places:

           Block<int> foo( Block<int> b ){
               if(b.size()==0)error();
               ...
               return b;
           }
   

main(){ Block<int> b2(100); ... Block<int> b1 = foo(b2); if(b1.size()==0)error(); }


Next topic: Accessing Block Elements
Previous topic: Creating Blocks of a Given Size

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004