How come a non-const reference cannot bind to a temporary object?

Why is it not allowed to get non-const reference to a temporary object, which function getx() returns? Clearly, this is prohibited by C++ Standard but I am interested in the purpose of such restriction, not a reference to the standard. struct X { X& ref() { return *this; } }; X getx() { return X();} … Read more

What is the (“spaceship”, three-way comparison) operator in C++?

While I was trying to learn about C++ operators, I stumbled upon a strange comparison operator on cppreference.com,* in a table that looked like this: “Well, if these are common operators in C++, I better learn them”, I thought. But all my attempts to elucidate this mystery were unsuccessful. Even here, on Stack Overflow I … Read more

How do I remove code duplication between similar const and non-const member functions?

Let’s say I have the following class X where I want to return access to an internal member: class Z { // details }; class X { std::vector<Z> vecZ; public: Z& Z(size_t index) { // massive amounts of code for validating index Z& ret = vecZ[index]; // even more code for determining that the Z … Read more