Topic: conversion to non-const


Author: SEEKAMP@RALVM5.VNET.IBM.COM (Chris Seekamp (441-7356(t/l 441)))
Date: Thu, 5 Aug 93 13:17:08 EDT
Raw View
I have a simple class, Token, where I want to guarantee it only has
one owner.  When I assign a Token to another, I clear out the value
in the Token it was assigned from.  I do the same with the copy
constructor.  Note, that I am using non-const arguments for both the
copy constructor and assignment operator, as shown below:
class Token
{
public:
   Token() {count_=0;}
   Token(Token & another)
   {
     count_ = another.count_;
     another.count_ = 0;
   }
   ~Token(){}
   void operator=(Token &another)
   {
      count_ = another.count_;
      another.count_ = 0;
   }
   .
   .
   .
private:
   unsigned int count_;
};
However, if I have any functions which return a Token (not a Token &
or Token *), and then do an assignment using the result of that
function, I get compile time error telling me that the 'Conversion from
"Token" to a reference to a non-const type "Token&" requires a
temporary.'  Thus, if I have a function
Token createToken(....) {....}
which creates a Token and then try:

Token aToken;
aToken = createToken(....);

I get the error message I described, pointing at the assignment
statement (e.g. aToken = ....).

So, my question is, is the compiler right?  The ARM says that you
can have non-const copy constructors and non-const assignment
operators, but if it turns out that I cannot have a function create
an instance of the class (a value, not a reference or pointer)
and then assign this to another instance using my non-const
assignment operator, the non-const assignment operator has little
use.

I know I can make the assignment operator const and "cast away const"
but I don't want to do that, because this is not a "conceptual
constness".  I really am modifying what I am assigning from and I want
that stated in the interface clearly.

I have seen recent discussion in comp.lang.c++ that implies that
there is some uncertainty about how temporaries are treated, and
assuming that a temporary has to be created when you return a new
instance of a class from a function, my problem may be related to
how these issues are resolved (i.e. does the created temporary have
to be const).  My compiler vendor has interpreted the standard to say
that compiler-generated temporaries are const.  Is this correct?
We have tried this on other compilers (e.g. Borland, Zortech) and
it did not flag an error.

Is there something in the standard that resolves this issue.  If
compiler-generated temporaries have to be const, does this mean
that support for non-const assignment operators should be removed
from the standard?