Re: assignment operator for classes with const data
Gavin Deane wrote:
LR wrote:
scroopy wrote:
Is it impossible in C++ to create an assignment operator for classes
with const data? I want to do something like this
class MyClass
{
const int m_iValue;
public:
MyClass(int iVal):m_iValue(iVal){}
MyClass operator=(const MyClass& mc)
{
m_iValue = mc.m_iValue; //not allowed
return *this;
}
Have you looked into const_cast?
I don't see how that will help in the OP's case. const_cast can't be
used to change an object that was declared const.
You snipped this:
"You may also find this of interest: http://www.gotw.ca/gotw/059.htm "
The OPs assignment operator is a little unusual in that he's not
returning a reference, however, I saw nothing in the OP that suggested
that a copy ctor and swap couldn't be added to this class, and using
form described in the link above...
MyClass &operator=(const MyClass &m) {
MyClass temp(m);
swap(temp);
return *this;
}
Implementing the copy ctor should be easy. MyClass::swap(MyClass &) has
the problem described by the title of the thread, hence my suggestion to
look into const_cast.
However, suppose that the op really does want something like (sorry,
typed in not cut and pasted)
class X {
const int m_;
public:
X operator=(const X &x) {
m_ = x.m_;
}
};
which won't work.
Instead, perhaps
class X {
const int m_;
public:
X operator=(const X &x) {
int &r = const_cast<int&>(m_);
r = x.m_;
}
};
I'm not 100% certain if this complies with the standard, however, it
seems to compile with no errors or warnings with Comeau's try it out,
doesn't get a warning from Gimpel's Blank Slate, except that we're
returning an X instead of a X&, and compiles and runs with the compiler
I normally use. Of course these last three cannot be taken as proof
that it is compliant. And it would certainly deserve some sort of
comment if put into production code.
My compiler will compile this too:
class X {
const int m_;
public:
X operator=(const X &x) {
const_cast<int&>(m_) = x.m_;
}
};
Of course, since what the OP was actually trying for seems to have been
a copy ctor, all of this may be besides the point.
LR