当我运行下面的代码:为什么C++标准库运算符接受rvalues?
std::string myString = "I'm a string.";
const std::string::iterator &myIterator = ++myString.begin();
char c = *myIterator;
std::cout << c << std::endl;
我得到一个分段错误(O3带编译优化)。我认为这是因为++
运营商返回std::string::iterator &
而不是std::string::iterator
,所以我们得到一个临时的参考。有没有原因为什么这不会导致编译错误?也就是说,为什么不是签名以下?
std::string::iterator &std::string::iterator::operator++() &;
甚至更好,为什么不规范需要以下特征,使我们能够处理没有问题,右值?
std::string::iterator &std::string::iterator::operator++() &;
std::string::iterator std::string::iterator::operator++() &&;
[无法重现](https://ideone.com/I9Z8De)。你确定这是因为这些线?在附注中,即使'++'返回引用,'myIterator'也不是引用,因此它将复制值 – Rakete1111
这工作正常。你能发布完整的代码吗? – Sumeet
是的,你是对的。我修改了这个例子,它现在应该会崩溃。 –