This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Functions returning expressions on maps

Tags: None
(comma "," separated)
gvissers
Registered Member
Posts
2
Karma
0
OS
I'm trying to write a wrapper function that returns an expression operating on a mapped array, but it looks like I'm doing it wrong. Here's a sample program:
Code: Select all
#include <iostream>
#include <Eigen/Core>

typedef Eigen::ArrayXd ColArray;
typedef ColArray::ConstAlignedMapType ColArrayMap;
typedef Eigen::CwiseUnaryOp< Eigen::internal::scalar_add_op<double>, const ColArray > PlusExpr;
typedef Eigen::CwiseUnaryOp< Eigen::internal::scalar_add_op<double>, ColArrayMap > PlusMapExpr;

ColArray v(3);

ColArrayMap mymap()
{
        return Eigen::ArrayXd::MapAligned(const_cast<const double*>(v.data()), v.size());
}

PlusExpr plusone()
{
        return v+1.0;
}

PlusMapExpr mapplusone()
{
        return mymap()+1.0;
}

int main()
{
        v << 1, 2, 3;

        std::cout << "v,        rows = " << v.rows() << "\n";
        std::cout << "map(v),   rows = " << mymap().rows() << "\n";
        std::cout << "v+1,      rows = " << plusone().rows() << "\n";
        std::cout << "map(v)+1, rows = " << mapplusone().rows() << "\n";

        return 0;
}

When I compile and run this, using the current development branch of Eigen, I get:
Code: Select all
$ g++ -Wall -W -I eigen testmap.cc -o testmap && ./testmap
v,        rows = 3
map(v),   rows = 3
v+1,      rows = 3
map(v)+1, rows = 4199135

So it looks like something is overwritten where it shouldn't. Doing anything more involved with the resulting expression than simply printing the number of rows will usually result in a segfault or a failed assertion.

So, is it possible to use maps in this way, and if so, what is the correct incantation? Any tips on how to fix this will be greatly appreciated.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
the problem is that mymap returns a temporary while Map objects are currenty nested by reference... Honestly I don't see why Map objects are not nested by value, I'll investigate.
gvissers
Registered Member
Posts
2
Karma
0
OS
ggael wrote:the problem is that mymap returns a temporary while Map objects are currenty nested by reference...

Right. That would explain the symptoms.
ggael wrote:Honestly I don't see why Map objects are not nested by value, I'll investigate.

Thanks for looking into this!


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], Yahoo [Bot]