Search code examples
c++visual-studio-2010constantsinitializer-list

Initialization Lists in Const Fields dont generate operator=


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;
}

Solution

  • The standard disallows it:

    C++03 12.8. Copying objects

    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.