dimanche 8 août 2021

Why does std::map::operator[] assignment require an argumentless constructor?

I have the following minimal example reproducing an error in my code:

#include <unordered_map>
#include <iostream>

class B 
{
public:
    B(int b) : m_b{ b } {}
    int m_b;
};

int main()
{    
    using std::cout, std::endl;
    std::unordered_map<int, B> ab{};

    ab[1] = B(3);
    //ab.insert(std::pair<int, B>(1, B(3)));

    cout << ab[1].m_b << endl;
}

This fails with a long and unwieldy error which basically amounts to saying that there is no constructor for B without any arguments. The error stems from ab[1] = B(3) Why is that needed? And why does using insert instead of operator[] not need that constructor?

Bonus points for why this line in my original code:

Vec2 pos{ m_orbits[&p].positionAtTime(m_time + dt) };

also requires a non - parameterized constructor. I could not reproduce that error in my minimal example, but m_orbits is an unordered map with pointers to Particle objects as keys and Orbit objects as values. positionAtTime is a const member function of Orbit that calculates the position of a particle in the orbit at a certain time.

Aucun commentaire:

Enregistrer un commentaire