mardi 31 mai 2022

Emplacing an instance with constant fields fails to compile (C++)

I have an example_class with two constant fields. When I try to emplace an object of that class into a std::vector, I get various errors such as "error: object of type 'example_class' cannot be assigned because its copy assignment operator is implicitly deleted". Does anyone know what is going on here? If I remove the const in example class, the code compiles without problems.

#include <vector>
#include <iostream>

using namespace std;

class example_class {
    public:
    example_class(int v1, int v2) : val1(v1), val2(v2) {}

    private:
    const int val1, val2;
};

int main() {

    vector<example_class> *vec = new vector<example_class>();
    vec->emplace(vec->begin() + 1, 13131, 12313);

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire