Search code examples
c++structcopy-assignment

Copy struct to array with const values


I'm trying to replace a struct value that has a const value in a non const array but it fails to compile with:

Object of type 'Foo' cannot be assigned because its copy assignment operator is implicitly deleted

Here is an example:

struct Foo {
    const int id;
    int value;
    Foo(): id(-1), value(-1) {}
    Foo(int id): id(id), value(0) {}
};


int main(int argc, const char * argv[]) {
    Foo foos[10];
    foos[0] = Foo(1234);
    return 0;
}

I'm coming from a swift background where that is valid as it copies the struct value into the array.

I tried making what I thought was a copy assignment operator but with const members what I tried didn't work either.

This is what I was trying to do for the copy assignment operator:

    Foo& operator= (Foo newVal) {
        // what do I put here!?
        return *this;
    };

Doing a memcpy to the array works but seems like the wrong sledgehammer for the job.

Being new at c++ I'm unsure what the correct pattern is for this type of flow.


Solution

  • C++ treats const very strictly. Copying such a struct will be painful if possible at all (without UB). Perhaps what you are really looking for is "readonly" instead? In that case you can make fields private with public getters/setters:

    struct Foo {
        public:
            Foo(): id(-1), value(-1) {}
            Foo(int id): id(id), value(0) {}
    
            int getId() const {
                return id;
            }
    
            int getValue() const {
                return value;
            }
    
            void setValue(int newValue) {
                value = newValue;
            }
    
        private:
            int id;
            int value;
    };