jeudi 7 juillet 2016

Why do the C++ standard library operators accept rvalues?

When I run the following code:

std::string myString = "I'm a string.";
const std::string::iterator &myIterator = ++myString.begin();
char c = *myIterator;
std::cout << c << std::endl;

I get a segmentation fault (compiling with O3 optimization). I assume this is because the ++ operator returns a std::string::iterator & rather than a std::string::iterator, and so we get a reference to a temporary. Is there a reason why this is not implemented to cause a compile error? I.e., why isn't the signature the following?

std::string::iterator &std::string::iterator::operator++() &;

Or even better, why doesn't the spec require the following signatures so that we can handle rvalues without a problem?

std::string::iterator &std::string::iterator::operator++() &;
std::string::iterator std::string::iterator::operator++() &&;

Aucun commentaire:

Enregistrer un commentaire