🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #960

Constructor can subvert constness (was ~const)

#960
From: Tom Ngo
Date: Fri, 22 Mar 1991 03:22
54 lines
2475 bytes
Twenty days ago, Reid Ellis <rae@utcs.toronto.edu> wrote:

rae> Tom Ngo <ngo@tammy.harvard.edu> writes:
rae> [Are there any ways to accomplish what casting away const does,
rae> without doing so explicitly?]
rae> 
rae> How about this?
rae> 
rae> struct foo {
rae>     foo();
rae>     int sometimes() const;
rae>     int nonconst();
rae>   private:
rae>     foo & fRef;
rae> };
rae> 
rae> foo::foo() : fRef(*this) {}
rae> 
rae> Then, if say "sometimes()" needs to do a non-const thing, it can
rae> simply say "fRef.nonconst()".
rae> 
rae> I guess this is essentially casting the const away, but the compiler
rae> won't make a peep about it.

Interesting!  This must be a violation of ARM 8.4.3 [References],
which states:

    A reference to a plain T can be initialized only with a plain T.

Assuming this rule is intended to apply to the initialization of a
reference in a constructor, it seems you have uncovered an issue that
really ought to be addressed in the ARM:  what is that status of a
constructor with regard to constness?  Should it be made possible, as
suggested by Jim Adcock <jimad@microsoft.UUCP>, for constructors to be
specified as const?  If so, how would a const constructor be permitted
to change data members?

When a const object is constructed, I suppose *this is considered
non-const until the constructor is done.  This provides a window of
opportunity to initialize a non-const pointer or reference that is
durable, i.e. will still be alive after the constructor is done.

Perhaps the ARM needs to specify explicit rules regarding the
initialization of such durable entities.  Clearly one should not be
able to initialize a non-const pointer or reference from this.  But
what about components of this?  Can someone come up with a concise
rule that covers all of the ways that the constness of an object might
be subverted by assignments to non-const pointers and references
during construction? 
--
  Tom Ngo
  ngo@harvard.harvard.edu
  617/495-1768 lab number, leave message
Technical Details
Message-ID: <NGO.91Mar21222244@tammy.harvard.edu>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!sdd.hp.com!think.com!hsdndev!husc6!ngo

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!sdd.hp.com!think.com!hsdndev!husc6!ngo
From: ngo@tammy.harvard.edu (Tom Ngo)
Newsgroups: comp.std.c++
Subject: Constructor can subvert constness (was ~const)
Message-ID: <NGO.91Mar21222244@tammy.harvard.edu>
Date: 22 Mar 91 03:22:44 GMT
Sender: news@husc6.harvard.edu
Distribution: comp
Organization: Harvard Chemistry Department
Lines: 54