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

前端 未结 2 738
暗喜
暗喜 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<int> 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.

    0 讨论(0)
  • 2020-12-20 12:13

    I think you will leave the container in an invalid state if you move out one of the elements, I would argue the need to allow that state at all. Second, if you ever need that, can't you just call the new object's move constructor like this:

    T copyObj = std::move(makeVector()[0]);

    Update:

    Most important point is, again in my opinion, that containers are containers by their nature, so they should not anyhow modify the elements inside them. They just provide a storage, iteration mechanism, etc.

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