Article View: comp.std.c++
Article #2051Casts to reference
From: Bryan Boreham
Date: Wed, 27 Sep 1995 16:54
Date: Wed, 27 Sep 1995 16:54
37 lines
1732 bytes
1732 bytes
Is anyone else alarmed that a cast to a reference type can silently
convert anything, even when the relevant object or pointer cast would
be disallowed?
E.g.:
struct { double x; } s;
double d = (double)s; // Error: Cannot cast from struct to double.
double &e = (double&)s; // this is OK
char *p = (char*)s; // Error: Cannot cast from struct to char*.
char &q = (char&)s; // fine
char*&r = (char*&)s; // no problem.
class A {};
class B : public virtual A {};
A* a;
B* b = (B*)a; // Error: Cannot cast from A* to B*.
B& c = (B&)a; // this is OK
I get the same answer from all the compilers I have available. Even
the ARM seems to rule out the last one, but the compilers don't mind.
Newcomers may be taught that references are "just like objects except
cheaper to copy", or "just like pointers except you don't have to
dereference them". As far as casting goes, references are dangerous.
Bryan Boreham, Front Office Development, Credit Suisse Financial Products
1 Cabot Square, London E14 4QJ, phone: +44 171 516 2058, fax:+44 171 516 2688
email: bboreham@csfp.co.uk
---
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Technical Details
Message-ID:
<MATT.95Sep27095444@physics10.Berkeley.EDU>Path:
arc1-ca.pugleaf.net!128.32.155.1!mattShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!128.32.155.1!matt From: bboreham@csfp.co.uk (Bryan Boreham) Newsgroups: comp.std.c++ Subject: Casts to reference Date: 27 Sep 1995 16:54:44 GMT Organization: <none> Approved: matt@physics10.Berkeley.EDU (Matt Austern) Message-ID: <MATT.95Sep27095444@physics10.Berkeley.EDU> NNTP-Posting-Host: physics10.berkeley.edu