Reduce the damage by adding “&&” to the end of the proxy class’s operator=
(And operator +=, -=, etc.)
Took me a lot of experimenting but I eventually found a way to mitigate the most common case of the problem, this tightens it so you can still copy the proxy, but once you’ve copied it to a stack variable, you can’t modify it and inadvertently corrupt the source container.
#include <cstdio>
#include <utility>
auto someComplexMethod()
{
struct s
{
void operator=(int A)&& {std::printf("Setting A to %i", A);}
};
return s();
}
int main()
{
someComplexMethod() = 4; // Compiles. Yay
auto b = someComplexMethod();
// Unfortunately that still compiles, and it's still taking a
// copy of the proxy, but no damage is done yet.
b = 5;
// That doesn't compile. Error given is:
// No overload for '=' note: candidate function not viable:
// expects an rvalue for object argument
std::move(b) = 6;
// That compiles, but is basically casting around the
// protections, aka shooting yourself in the foot.
}