For some reason , the compiler cannot generate the operator= for this class because of the initialization of the const field _constFoo, I just wanna know why. Using VS2010.
class Foo {
public:
Foo(int f) : _constFoo(f) { }
int getFoo() const { return _constFoo; }
//void operator=(const Foo &f) { memcpy(this, &f, sizeof(Foo)); }
private:
const int _constFoo;
};
int main(int argc, char *argv[])
{
Foo f(5);
cout << f.getFoo() << endl;
f = Foo(6); //error C2582: 'operator =' function is unavailable in 'Foo'
cout << f.getFoo() << endl;
}
The standard disallows it:
12) [...] A program is ill-formed if the class for which a copy assignment operator is implicitly defined has:
- a non-static data member of
const
type, or- a non-static data member of reference type, or
- a non-static data member of class type (or array thereof) with an inaccessible copy assignment operator, or
- a base class with an inaccessible copy assignment operator.
[...]
emphasis mine.
So your program is ill-formed. By not defining your own assignment operator, the compiler attempts to implicitly define one.