Is returning a const& valid?
Hi
I have run into a problem regarding references to temporary objects.
I solved the problem by
returning a const reference to the temporary object, this feels very
wrong to me.
I have been using Blitz++ Arrays, one aspect i dislike is that
assignment to an uninitialised
blitz::Array copies 0 elements.
I wrote a proxy class whose operator= references the source array
instead of copying elements.
template<typename T, int N>
class blitz_array_proxy
{
public:
blitz_array_proxy(blitz::Array<T, N>& ar)
: ar_(ar) { }
blitz_array_proxy& operator=(const blitz::Array<T, N>& ar)
{
ar_.reference(ar);
return *this;
}
private:
// Silence level 4 warning in Visual C++ 2005
blitz_array_proxy& operator=(const blitz_array_proxy& bap);
blitz::Array<T, N>& ar_;
};
and a helper function to deduce template types,
template<typename T, int N>
blitz_array_proxy<T, N> init(blitz::Array<T, N>& ar)
{
return blitz_array_proxy<T, N>(ar);
}
This can be used as follows,
Array<double, 1> a(6);
Array<double, 1> b;
b = a; // Copies 0 elements
init(b) = a; // Equivalent to b.reference(a);
I ran into a problem when I tried to combine this with Boost Tuple as
I wish to return
multiple blitz::Arrays from a function. The problem is that tuples'
tie function takes
its parameters as references in order to alter them,
tie(init(b)) = make_tuple(a); // Compile Error - reference to
temporary
I found that I could work around this by altering blitz_array_proxy's
operator= to,
const blitz_array_proxy& operator=(const blitz::Array<T, N>& ar) const
{
ar_.reference(ar);
return *this;
}
and changing the helper function as follows,
template<typename T, int N>
const blitz_array_proxy<T, N>& init(blitz::Array<T, N>& ar)
{
const blitz_array_proxy<T, N>& r = blitz_array_proxy<T, N>(ar);
return r;
}
This allows the program to compile and run successfully, it has also
worked with multiple
element tuples. I've only been able to try this on Visual C++ 2005.
Is the code valid?
Is there an alternative solution?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]