I have a struct with a std::map of pointers inside it. I’m trying to do the following:
template <class T>
struct Foo
{
std::map<std::string, T*> f;
T& operator[](std::string s)
{
return *f[s];
}
}
and then use it like this:
Foo<Bar> f;
f["key"] = new Bar();
but the way it’s written, it crashes the program. I also tried like this:
T* operator[](std::string s)
{
return f[s];
}
but it doesnt compile. It says "lvalue required as left operand of assignment" on the f["key"] = new Bar() line.
I expected it to be easy since I’m trying to return a pointer and I’m storing a pointer. What is wrong with my code?
The correct way of doing this is:
and call it like
f["key"] = new Bar().EDIT: You should start passing non-basic types by const reference where you can: