通过引用返回stl映射的正确方法/这个行为是否定义良好?

Ian*_*ath 8 c++ stl reference

我有2个类,其中一个map<string, vector<string> >我希望能够在其他类中使用它.这是我的代码:

class a
{
    map<string, vector<string> > m;
    public:
    const map<string, vector<string> > & get()
    {
        return m;
    }
};

class b
{
    a obj;
    public:
    void test()
    {
        map<string, vector<string> > m= obj.get();
        // and then print
    }
};

int main(int argc, char ** argv)
{
    b bobj;
    bobj.test();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我返回地图的方式class a是否正确?它工作,但我只想确认它是否正确完成/我很幸运/任何其他关于代码的评论.

谢谢您的帮助.

sbi*_*sbi 13

如果您不想更改地图b::test(),则不应复制它:

const map<string, vector<string> >& m = obj.get(); // note the const &
Run Code Online (Sandbox Code Playgroud)

我的反对意见:

  1. 专业:a::get()应该是const:

    const map<string, vector<string> > & get() const // note the const at the end
    
    Run Code Online (Sandbox Code Playgroud)
  2. 轻微:我会使用地图的类型创建别名typedef.

    typedef map<string, vector<string> > my_map_t;
    
    Run Code Online (Sandbox Code Playgroud)
  3. 轻微:我完全看不到b它的用途.

鉴于这些,我的代码看起来像这样:

class a
{
    public:
      typedef map<string, vector<string> > my_map_t;

      const my_map_t & get() const {return m;}

    private:
      my_map_t m;
};

void test(const a& obj)
{
    const a::my_map_t& m = obj.get();
    // and then print
}

int main()
{
    a obj;
    test(obj);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)