Opened 6 years ago
Closed 6 years ago
#12307 closed Bugs (fixed)
Copy assignment from const ref handled differently in C++11/C++98
| Reported by: | Owned by: | Ion Gaztañaga | |
|---|---|---|---|
| Milestone: | To Be Determined | Component: | move |
| Version: | Boost 1.59.0 | Severity: | Problem |
| Keywords: | Cc: |
Description
There is a difference in the handling of copy assignment when using Boost.Move between C++11 and C++98:
#include <boost/move/move.hpp>
#include <cassert>
class Foo{
BOOST_COPYABLE_AND_MOVABLE(Foo)
public:
int i;
explicit Foo(int val): i(val){}
Foo(BOOST_RV_REF(Foo) obj): i(obj.i) {}
Foo& operator=(BOOST_RV_REF(Foo) rhs){ i = rhs.i; rhs.i = 0; return *this; }
Foo& operator=(BOOST_COPY_ASSIGN_REF(Foo) rhs){ i = rhs.i; return *this; } //(1)
template<class OTHER>
Foo& operator=(const OTHER& rhs){ i = rhs.j; return *this; } //(2)
};
struct Bar{
int j;
explicit Bar(int val): j(val){}
};
int main(){
Foo foo2(2);
// Working cases
Foo foo1(1);
Bar bar(3);
assert(foo1.i == 1);
assert(foo2.i == 2);
assert(bar.j == 3);
foo2 = foo1;
assert(foo1.i == 1);
assert(foo2.i == 1);
foo1 = bar;
assert(foo1.i == 3);
foo2 = boost::move(foo1);
assert(foo1.i == 0);
assert(foo2.i == 3);
// BUG
const Foo foo4(4);
foo2 = foo4; // Calls (1) in C++11 but (2) in C++98 which fails
assert(foo2.i == 4);
assert(foo4.i == 4);
return 0;
}
This is slighlty different than https://svn.boost.org/trac/boost/ticket/12194 which was fixed with https://github.com/boostorg/move/pull/9 but kind of releated.
Change History (3)
comment:1 by , 6 years ago
comment:2 by , 6 years ago
I guessed that. But it is not documented and the current documentation statest that this should be possible: http://www.boost.org/doc/libs/1_61_0/doc/html/move/how_the_library_works.html ("const rvalue and lvalues, bind to const ::boost::rv< TYPE >&")
My first guess for a fix would be based on:
#define BOOST_COPYABLE_AND_MOVABLE(TYPE)\
public:\
TYPE& operator=(TYPE &t)\
{ this->operator=(*BOOST_MOVE_TO_RV_CAST(const ::boost::rv<TYPE>*, &t)); return *this;}\
so what about:
#define BOOST_COPYABLE_AND_MOVABLE(TYPE)\
public:\
TYPE& operator=(TYPE &t)\
{ this->operator=(*BOOST_MOVE_TO_RV_CAST(const ::boost::rv<TYPE>*, &t)); return *this;}\
const TYPE& operator=(const TYPE &t)\
{ this->operator=(*BOOST_MOVE_TO_RV_CAST(const ::boost::rv<TYPE>*, &t)); return *this;}\
or similar. Not sure if this works for all cases or at all, but this would fulfill the "const lvalues bind to const rv&" part.
If this does not work, please add it to the docu.
comment:3 by , 6 years ago
| Resolution: | → fixed |
|---|---|
| Status: | new → closed |
Documented limitation and possible workaround in commit:
https://github.com/boostorg/move/commit/cfd6be4ab46223917cb79e7dd856f582df587d7d

There is no much the emulation can do in this case. It's a limitation that should be documented.