Re: assignment operator and const members
clcppm-poster@this.is.invalid (Jonathan Jones) wrote (abridged):
I guess the problem that lead to my original question (wanting
assignment to work with const members), is that C++ doesn't fully
support it. What I _really_ want is this:
struct Object
{
Object(int data, ...) : data_(data), ... {}
Object(const Object& r) : data_(r.data_), ... {}
foo() { ... } // can modify everything except data_
bar() { ... } // can modify everything except data_
baz() { ... } // can modify everything except data_
Object& operator=(const Object& r) { data_=r.data; ... }
private:
const int data_;
// lots of non-const data
};
The class is a unit in C++. Such problems as this can often be addressed
by using multiple classes, eg:
class Data {
protected:
Data( int d ) : data_d() {}
int data() const { return data_; }
private:
int data_;
};
struct Object : private Data {
// ...
};
Now Object methods can use data(), but they can't change data_ by
accident. Only by doing:
Data::operator=( Data( value ) );
which is here the moral equivalent of a const_cast and not likely to
happen by accident. (Except in Object::operator=(), which the compiler
will now generate for you.)
I know you could const-qualify all the member functions, while
declaring all the other data as mutable, but that seems ugly at
best.
It seems actively wrong, because the const-qualified members would be
claiming not to modify the observable state of the object, when they
would so modify it. Generally you should only use mutable for things like
caches, which don't affect the observable state.
If data_ were truly const, then you wouldn't have an assignment operator
that changed it. Instead clients would have to use pointers and write
code like:
// Object object( 0 );
Object *pObject = new Object( 0 );
// ...
// object = Object( 1 );
delete pObject;
pObject = new Object( 1 );
explicitly destroying the old object and constructing a new one. Which is
more or less the code you were trying to put into operator=(), but that's
the wrong place for it.
-- Dave Harris, Nottingham, UK.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]