|
Boost : |
Subject: [boost] [Operators] Update, const-correctness and operator chaining
From: Andrew Ho (helloworld922_at_[hidden])
Date: 2013-07-01 17:42:41
Hi, I was doing some testing with Daniel Frey/Marc Glisse's proposed 4-
overload set
for binary operators.
For reference, here's the overload set applied to commutative addition:
friend T operator +( const T& lhs, const T& rhs)
{
T nrv(lhs);
nrv += rhs;
return nrv;
}
friend T operator +(T&& lhs, const T& rhs)
{
return std::move(lhs += rhs);
}
friend T operator +(const T& lhs, T&& rhs)
{
T nrv(lhs);
nrv += boost::move(rhs);
return nrv;
}
friend T operator +(T&& lhs, T&& rhs)
{
return boost::move(lhs += boost::move(rhs));
}
This allows this to be done:
val1 + val2 = val3;
changing the return type to const T would allow the compiler to catch this,
but now
doing val1 + val2 + val3 must always use copy semantics instead of move
semantics.
I can't think of a way which would fix this issue without breaking the use
of move
semantics. How should we proceed with this? It's obviously bad usage, but
the
compiler should be able to catch this since it's easy to mistype + as =.
Interestingly enough, doing testing with std::string shows the same
"problem":
std::string str1("hello"), str2(" "), str3("world");
str1 + str2 = str3;
I tested this issue with std::string and found it in vs2012, gcc 4.3.2, and
mingw/gcc 4.8.0. I don't have access to a compiler which pre-dates
C++0x/C++11 so I
don't know if this issue has always been present. Compiling with gcc 4.8.0
with -
std=c++03 still has the issue.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk