Re: [eigen] is returning Eigen::Ref objects legit? |
[ Thread Index |
Date Index
| More lists.tuxfamily.org/eigen Archives
]
在 2013 五月 20 週一 15:38:12,Sébastien Barthélémy 寫道:
> Hello,
>
> I'm giving new Eigen::Refs a try and thought they might be a handy
> type to return (by const ref), especially when the implementation
> knows the matrix size at compile time but the caller does not.
Yes, it's a wrapper of reference.
> However, I'm not sure they are intended to be returned. The doc says
> "This class permits to write non template functions taking Eigen's
> object as parameters".
>
> Moreover my small test gets a "returning reference to temporary"
> warning at compile time and a std::bad_alloc exception at runtime.
> This does not sound good ;).
Temporary variables are deconstructed at the end of the statement (;), local
ones at the end of the block (}). When returning a reference to an in-scope
variable, the variable is deconstructed, making the reference pointing to
'nothing'. One says the reference is 'lost'. ("Lost" as in "lost in space")
However, returning a reference to an out-scope variable is safe. The variable
is not deconstructed after the execution of the function.
### example.cpp
#include <cstdio>
int glob = 3;
int& safe1(int& arg)
{ return arg; }
int& safe2()
{ return glob; }
int& dangerous1(int arg) // arg
{ return arg; }
int& dangerous2()
{
int tmp = 2;
return tmp;
}
int main()
{
printf("%d\n", safe1(glob)); // &glob == &arg
printf("%d\n", safe2());
printf("%d\n", dangerous1(glob)); // &glob != &arg
printf("%d\n", dangerous2());
return 0;
}
### EOF
> Could you please confirm in either way?
>
> Example and backtrace are attached just in case.
>
> Thanks!
--
何震邦 | Chen-Pang He | 0918-319823
jdh8@xxxxxxxxxxxxxx | http://jdh8.no-ip.org