Why isn't operator[] overloaded for lvalues and rvalues?

前端 未结 2 825
暗喜
暗喜 2020-12-20 11:54

The standard C++ containers offer only one version of operator[] for containers like vector and deque. It returns a

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-20 12:10

    Converting comment into answer:

    There's nothing inherently wrong with this approach; class member access follows a similar rule (E1.E2 is an xvalue if E1 is an rvalue and E2 names a non-static data member and is not a reference, see [expr.ref]/4.2), and elements inside a container are logically similar to non-static data members.

    A significant problem with doing it for std::vector or other standard containers is that it will likely break some legacy code. Consider:

    void foo(int &);
    std::vector bar();
    
    foo(bar()[0]);
    

    That last line will stop compiling if operator[] on an rvalue vector returned an xvalue. Alternatively - and arguably worse - if there is a foo(const int &) overload, it will silently start calling that function instead.

    Also, returning a bunch of elements in a container and only using one element is already rather inefficient. It's arguable that code that does this probably doesn't care much about speed anyway, and so the small performance improvement is not worth introducing a potentially breaking change.

提交回复
热议问题