The standard C++ containers offer only one version of operator[]
for containers like vector<T>
and deque<T>
. It returns a T&
(other than for vector<bool>
, which I'm going to ignore), which is an lvalue. That means that in code like this,
vector<BigObject> makeVector(); // factory function
auto copyOfObject = makeVector()[0]; // copy BigObject
copyOfObject
will be copy constructed. Given that makeVector()
returns an rvalue vector
, it seems reasonable to expect copyOfObject
to be move constructed.
If operator[]
for such containers was overloaded for rvalue and lvalue objects, then operator[]
for rvalue containers could return an rvalue reference, i.e., an rvalue:
template<typename T>
container {
public:
T& operator[](int index) &; // for lvalue objects
T&& operator[](int index) &&; // for rvalue objects
...
};
In that case, copyOfObject
would be move constructed.
Is there a reason this kind of overloading would be a bad idea in general? Is there a reason why it's not done for the standard containers in C++14?
container[0]
empty/moved makes repeat access of the same element tricky(unless say,container.at(0)
is not overloaded for rvalue), and 2)auto& ref = container[0]
will not work everywherevector<int> f(); void g(int &);
,g(f()[0])
will suddenly stop working, or, if there's also avoid g(const int &);
, silently go to a different overload.E1.E2
is an xvalue ifE2
names a non-static data member andE1
is an rvalue).std::experimental::optional
also uses a similar design, though I can't remember whether the&&
version for that returnsT
orT&&
.