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

Strange behavior for const reference to temporary objects

Tags: None
(comma "," separated)
M.X. Grey
Registered Member
Posts
1
Karma
0
Before I get too much into the details of the strange behavior that I'm witnessing, I thought I'd illustrate the situation with the simplest possible source code example:

Code: Select all
#include <Eigen/Core>
#include <iostream>

int main()
{
    Eigen::MatrixXd M = Eigen::MatrixXd::Identity(3,3);
    Eigen::Vector3d v(1,2,3);

    const Eigen::VectorXd& correctResult = (M*v).eval();
    const Eigen::VectorXd& wrongResult = M*v;
    Eigen::VectorXd alsoCorrectResult = M*v;

    std::cout << "Wrong:   " << wrongResult.transpose() << std::endl;
    std::cout << "Correct: " << correctResult.transpose() << std::endl;
    std::cout << "Correct: " << alsoCorrectResult.transpose() << std::endl;
}


This produces the following output on my machine:

Wrong: 0 2 3
Correct: 1 2 3
Correct: 1 2 3


Note that you need to compile in Release mode to get this output. Debug mode will simply throw a runtime assertion.

I believe I've tracked down the primary culprit: lazy evaluation. I believe what's happening is that Eigen's use of Expression Templates is making it so that no temporary is created (or is not being created in a way that I would have expected), and therefore it is not leaving a correct temporary object for wrongResult to refer to.

First, I would like to ask: Is my evaluation of the situation correct? Is there anything going on that I'm overlooking?

Second, is this issue with const references discussed anywhere in Eigen's documentation? Considering the popularity of using const references to allow the compiler to perform optimizations, this seems like an important situation for the documentation to mention. I personally couldn't find anything in the documentation mentioning this issue.

Third, I noticed that if wrongResult is a const Eigen::Vector3d& instead, there is no error. I don't know if this is due to undefined behavior (i.e. it came out correct because of a coincidence) or if the issue simply does not exist for statically-sized matrices.

Thanks for any feedback!
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
See this answer: viewtopic.php?f=74&t=123602#p324162

Even though the two problems are different, the explanation is the same. This issue is gone in the devel branch.


Bookmarks



Who is online

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