指针映射的数组下标运算符

Array subscript operator for pointer map

本文关键字:下标 运算符 数组 映射 指针      更新时间:2023-10-16

我有一个结构,里面有一个std::指针映射

template <class T>
struct Foo
{
    std::map<std::string, T*> f;
    T& operator[](std::string s)
    {
        return *f[s];
    }
}

然后像这样使用:

Foo<Bar> f;
f["key"] = new Bar();

但它的编写方式会使程序崩溃。我也试过这样做:

T* operator[](std::string s)
{
    return f[s];
}

但它不能编译。它在f["key"] = new Bar()线上显示"lvalue required as left operand of assignment"

我希望它很容易,因为我正在尝试返回一个指针,并且我正在存储一个指针。我的代码出了什么问题?

正确的方法是:

T*& operator[](std::string s)
{
    return f[s];
}

并将其称为CCD_ 3。

EDIT:您应该开始通过const引用传递非基本类型,您可以:

T*& operator[](const std::string& s)