C++ 错误 C2280。为什么结构体不可复制

sna*_*ulX 0 c++ struct copy-constructor

我在 C 项目中的头文件中有一个结构。

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 *);
};
Run Code Online (Sandbox Code Playgroud)

在链接这个 C 项目的 C++ 项目中,我有这个结构,它使用 asEntryAllocator<tgMethod>但编译器给出错误: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;
};
Run Code Online (Sandbox Code Playgroud)

为什么tgMethod不可复制?我需要更改什么来修复此错误并保存程序逻辑?

Dre*_*ann 7

为什么 tgMethod 是不可复制的?

tgMethod可以通过复制构造进行复制,但不可分配

你们班tgMethod有几名const成员。

const enum tgAccessModifier access;
const enum tgMethodKind kind;

const tgParams params;
Run Code Online (Sandbox Code Playgroud)

const成员不能更改,因此构造tgMethod对象不能完全更改。

由于tgMethod::operator =(const tgMethod &)会改变对象,因此不能默认实现,编译器选择删除该函数。

我需要更改什么来修复此错误

您可以使成员成为非const.

或者您可以手动实现您自己的tgMethod::operator =(const tgMethod &),以某种方式实现您的“任务”,而无需修改const成员。