rvalue ref-qualifiers for STL containers

前端 未结 1 1748
迷失自我
迷失自我 2021-01-18 19:08

Why element access member functions of STL containers, e.g. std::array::operator[] or std::vector::operator[] do not have rvalue ref-qualifier over

相关标签:
1条回答
  • 2021-01-18 19:57

    There isn't a particular problem with adding ref-qualifiers to everything that returns references, however that basically doubles the number of members, which will generally have identical implementations apart from wrapping the return in std::move.

    class A
    {
        int a;
    
        int& operator[](std::size_t pos) & { return a; }
        int&& operator[](std::size_t pos) && { return std::move(a); }
    };
    

    The standard library has declined to provide these overloads, in the same way that it has declined to provide many volatile overloads. In this case, you can just std::move the & value, where you need it.

    If you are writing your own containers, then there is no safeness reason to avoid such overloads. It does increase the maintenance burden, so I would advise against it.

    0 讨论(0)
提交回复
热议问题