Re: operator class&() { return *this; } considered harmful?
On 30 out, 03:22, michael.norr...@nicta.com.au (Michael Norrish)
wrote:
I was wondering if there were any serious gotchas with including a
conversion to class& in a class's public interface.
Consider
#include <iostream>
using namespace std;
class C {
int fld;
public:
C(int x) : fld(x) {}
C(const C &r) : fld(r.fld) {}
int get_val() { return fld; }
operator C&() { return *this; }
};
C f()
{
C temp(2);
return temp;
}
int main()
{
C &x = f();
cout << "x = " << x.get_val() << endl;
return 0;
}
Without the operator C&, I can't initialise the reference x in main
(by 8.5.3, para 5). But with it in place, it seems to me as if the
language in 12.2 para 5 then guarantees that the object nominally
allocated in f will actually have a lifetime equivalent to the scope
of main's body.
But maybe there's something I'm missing?
You are missing rvalue references.
int main()
{
C&& x = f();
cout << "x = " << x.get_val() << endl;
return 0;
}
This new kind of reference is now part of the draft standard.
This is the explanatory paper:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1690.html
This is the last paper with proposed wording before inclusion in the
draft:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2118.html
--
Pedro Lamar?o
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]