Home > Software design >  C error C2280. Why struct is non-copyable
C error C2280. Why struct is non-copyable

Time:09-07

I have a struct inside header file in C project.

struct tgMethod {
    const char *name;
    const enum tgAccessModifier access;
    const enum tgMethodKind kind;
    tgTypeRef return_type;
    const tgParams params;
    const tgMethod *overrides;
    const void *userptr;
    const tgObject *(*methodptr)(tgObject *, size_t, tgObject *, void *);
};

In C project which links this C project I have this struct which using as EntryAllocator<tgMethod> but compiler gives error: error C2280: "tgMethod &tgMethod::operator =(const tgMethod &)": attempting to reference a deleted function

template<typename T>
struct EntryAllocator {
public:
    EntryAllocator() : EntryAllocator(1 << 7) { }

    explicit EntryAllocator(size_t max_size) :
                _start(0), _count(0), _capacity(max_size), _data((T*)calloc(max_size, sizeof(T)))
    { }

    ~EntryAllocator() {
        free(_data);
    }

    void Begin() {
        _start  = _count; // move '_start' to the end of filled data
        _count = 0;
    }

    void Append(T elem) {
        _data[_count  ] = elem;
        if (_start   _count > _capacity) {
            _capacity <<= 1; // *= 2 but faster
            _data = (T*) realloc(_data, _capacity * sizeof(T));
        }
    }

    void End(T **out_data, size_t &count) {
        *out_data = &_data[_start];
        count = _count;
    }

    void Trim() {
        _capacity = _start   _count;
        _data = (T*) realloc(_data, _capacity * sizeof(T));
    }

    [[nodiscard]] size_t GetCapacity() const { return _capacity; }
    [[nodiscard]] size_t GetCount() const { return _count; }
    [[nodiscard]] size_t GetLength() const { return _count   _start; }
    [[nodiscard]] T* GetRawData() const { return _data; }

private:
    size_t _start;
    size_t _count;
    size_t _capacity;
    T* _data;
};

Why tgMethod is non-copyable? What I need to change to fix this error and save the logic of program?

CodePudding user response:

Why tgMethod is non-copyable?

Your class tgMethod has several const members.

const enum tgAccessModifier access;
const enum tgMethodKind kind;

const tgParams params;

const members can not change, therefore a constructed tgMethod object can not change.

Since tgMethod::operator =(const tgMethod &) would change the object, it can not be default-implemented, and the compiler chooses to delete this function.

What I need to change to fix this error

You can make the members non-const.

Or you can manually implement your own tgMethod::operator =(const tgMethod &) that somehow achieves your "assignment" without modifying the const members.

  • Related