Re: [eigen] std::swap doesn't work on Map

[ Thread Index | Date Index | More lists.tuxfamily.org/eigen Archives ]


Hi,

The std::swap not working correctly on Eigen::Map: this is to be expected since
http://www.cplusplus.com/reference/algorithm/swap/
the generic swap implementation is:

template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
}

In the case of Map, the Map object 'c' created here is a copy of the
Map object a, so they share the same memory, so the code is equivalent
to:

  a = b; b = a;

Which explains your wrong results.

Normally we could consider fixing this by providing a partial template
specialization of std::swap for Eigen types, but the big problem is
that std::swap takes only 1 template parameter and expects both sides
to be of the same type, and this is not always the case with Eigen
swap on expressions. We could still catch the case where both sides
have the same type, but I'm not sure what to do then. If we let that
work, it's awkward that we require both sides to have the same type in
std::swap and not in .swap(). If we want to emit an error, it's hard
to do because of SFINAE (so generating an error there would simply
discard the specialization.). I have to read back the rules of SFINAE,
perhaps it will work to let our std::swap specialization call another
function from where we trigger an error...

Benoit

2010/4/4 Manoj Rajagopalan <rmanoj@xxxxxxxxx>:
> Hi eigen users/developers,
>
>   I create two std::vector<double> objects (v1 and v2), and instantiate
> Eigen::Map<VectorXd> objects for each (v1_map and v2_map). I'd like to point
> out two behaviors and ask if these are bugs or features.
>
> Before swap:
>        v1_stl   = [1 2 3 4 5 ]'
>        v2_stl   = [10 11 12 13 14 ]'
>        v1_eigen = [1 2 3 4 5]'
>        v2_eigen = [10 11 12 13 14]'
>
>
> CASE 1: Using v1.swap(v2)
> After swap:
>        v1_stl   = [10 11 12 13 14 ]'
>        v2_stl   = [1 2 3 4 5 ]'
>        v1_eigen = [1 2 3 4 5]'
>        v2_eigen = [10 11 12 13 14]'
>
>
> CASE 2: using std::swap(v1_map, v2_map)
> After swap:
>        v1_stl   = [10 11 12 13 14 ]'
>        v2_stl   = [10 11 12 13 14 ]'
>        v1_eigen = [10 11 12 13 14]'
>        v2_eigen = [10 11 12 13 14]'
>
>  The behavior in Case #1 can be explained: my STL implementation is swapping
> pointer data members to allocated memory in the STL vector classes. Since my
> Eigen::Map<> objects are instantiated using these pointers, the STL vector
> swap shouldn't affect my Eigen::Map<> objects.
>
>   The behavior in Case #2 however seems to be buggy to me. Should I file a
> bug report of some sort on the issue tracker?
>
> Thanks,
> Manoj
>
>
>



Mail converted by MHonArc 2.6.19+ http://listengine.tuxfamily.org/