std::map 的 operator[]函数返回左值引用,即使映射本身是右值。
T& operator[]( const Key& key );
这会导致使用未定义的行为,例如 this one .为什么没有像下面这样的左值和右值重载?是否有任何其他 map 实现使用此类重载?
T& operator[]( const Key& key ) &;
T operator[]( const Key& key ) &&;
最佳答案
#include <iostream>
#include <map>
bool silly_test( int& lhs, int& rhs ) { return lhs == rhs; }
std::map<int, int> silly_map() {
std::map<int, int> retval;
retval[0] = 0;
return retval;
}
int main() {
std::cout << silly_test( silly_map()[0], silly_map()[0] ) << "\n";
}
以上代码在 C++03 中是合法的,如果我们按照您的建议进行更改,则该代码是非法的。
虽然上面的代码很愚蠢,但它是您的更改可以破坏事情的一个例子。
对 this
的右值引用在 C++11 标准化后期添加。在周期后期对标准容器进行潜在的重大更改可能不是一个好主意。
我鼓励您提出建议,将上述更改纳入 C++1z 的标准。它可能不实用,但乍一看似乎是个不错的主意,因为它破坏的代码类型很奇怪(可能应该被破坏)。
关于c++ - 从右值对象返回左值引用的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21682669/