Article View: comp.std.c++
Article #2058Re: Casts to reference
From: Steve Clamage
Date: Wed, 27 Sep 1995 18:49
Date: Wed, 27 Sep 1995 18:49
38 lines
1945 bytes
1945 bytes
In article 95Sep27095444@physics10.Berkeley.EDU, bboreham@csfp.co.uk (Bryan Boreham) writes: > >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? No, and the reference cast is allowed only if the comparable pointer cast is allowed anyway. In any event, you should not use old-style casts at all. If you use static_cast or dynamic_cast, the cast will be permitted only if it is safe. Otherwise it will fail at compile time with an error, or at run time with a null return or a "bad_cast¨ exception. > > A* a; > B* b = (B*)a; // Error: Cannot cast from A* to B*. > B& c = (B&)a; // this is OK The pointer cast may be a programming error, but is allowed by the language rules. The old-style pointer cast says "Trust me, I know what I am doing." The compiler must allow it. >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. No, old-style casts are dangerous, period. References are merely not an exception. --- Steve Clamage, stephen.clamage@eng.sun.com --- [ 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.95Sep27114918@physics10.Berkeley.EDU>Path:
arc1-ca.pugleaf.net!128.32.155.1!mattReferences:
<MATT.95Sep27095444@physics10.Berkeley.EDU>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!128.32.155.1!matt From: clamage@Eng.Sun.COM (Steve Clamage) Newsgroups: comp.std.c++ Subject: Re: Casts to reference Date: 27 Sep 1995 18:49:18 GMT Organization: Sun Microsystems Inc. Approved: matt@physics10.Berkeley.EDU (Matt Austern) Message-ID: <MATT.95Sep27114918@physics10.Berkeley.EDU> References: <MATT.95Sep27095444@physics10.Berkeley.EDU> Reply-To: clamage@Eng.Sun.COM NNTP-Posting-Host: physics10.berkeley.edu