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

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

提交回复
热议问题