I am working on a container who's subscript operator returns a wrapper reference, like this:
my_container::reference my_container::operator[](std::size_t i);
The internal element representation of the container cannot be directly referenced and thus needs the proxy object. The reference itself has deleted copy & move constructors, and all operations are only defined for rvalue references.
However, a problem arises when deducing the wrapper object via auto
or decltype(auto)
.
For example, in the following code:
my_container bar();
auto foo(std::size_t i)
{
my_container c = bar();
return c[i];
}
auto
deduces to my_container::reference
instead of my_container::value_type
, since the reference proxy is an object type, and RVO guarantees that no copy- or move-constructors are being called. This is a problem, since in the above code a stack reference is being returned.
Is there any way to prevent such behavior? To my knowledge there is no way to bypass RVO, but perhaps I am missing something.
Edit: To give a bit more context, the container is a bit-mask over a vector of integers. Any assignments to the elements must also mask the assigned-to value, which is why the proxy reference is needed.