From 192223908379197681
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: 109fba,515fa24b8aaed57
X-Google-Attributes: gid109fba,public
X-Google-Thread: f78e5,515fa24b8aaed57
X-Google-Attributes: gidf78e5,public
From: ark@research.att.com (Andrew Koenig)
Subject: Re: Example in "The C++ Workbook" by Wiener and Pinson
Date: 1995/07/20
Message-ID: <DBzuD7.BGq@research.att.com>#1/1
X-Deja-AN: 106600135
references: <3ujj8d$o4m@scapa.cs.ualberta.ca>
organization: AT&T Bell Laboratories, Murray Hill NJ
newsgroups: comp.lang.c++,comp.std.c++

In article <3ujj8d$o4m@scapa.cs.ualberta.ca> kirill@sawnlk.cs.ualberta.ca (Kirill Richine) writes:

> The book "The C++ Workbook" by Richard S. Wiener and Lewis J. Pinson
> (Addison-Wesley) gives the following example

> #include <stdio.h>

> void swap(void *&item1,void *&item2)
> {
>   void *temp=item1;
> 
>   item1=item2;
>   item2=temp;
> }

OK ... so this function should swap two pointers to void...

> main()
> {
>   int *i=new int;
>   int *j=new int;

but i and j aren't pointers to void, they're pointers to int...

>   *i=5;
>   *j=20;
>   swap(i,j);

so this shouldn't work.  What should happen is that the compiler should
refuse to execute your program, but once upon a time (i.e. more than five years
ago) it used to be legal to bind a reference to an lvalue of the wrong type
and the compiler would quietly create a temporary -- so your compiler merely
gives a warning instead of an error.

>   printf("*i=%d *j=%d\n",*i,*j);

>   float *x=new float;
>   float *y=new float;

>   *x=5.0;
>   *y=20.0;
>   swap(x,y);

Exactly the same problem here, of course.

>   printf("*x=%f *y=%f\n",*x,*y);
> }

A much better way to write swap:

	template<class T> void swap (T& x, T& y)
	{
		T t = x;
		x = y;
		y = t;
	}
-- 
				--Andrew Koenig
				  ark@research.att.com



