Re: Reference vs Pointer in clone idiom
On Sep 3, 9:56 pm, Noah Roberts <roberts.n...@gmail.com> wrote:
mathieu wrote:
Is the following legal (*). I am reading:
http://www.parashift.com/c++-faq-lite/references.html#faq-8.6
But I am not sure I understand if in my case I should prefer
pointer over reference since new will throw and I will never
dereference a NULL pointer.
(*)
struct A
{
virtual A& clone() { return *new A; }
};
struct B : public A
{
B& clone() { return *new B; }
};
int main()
{
A a;
A ©a = a.clone();
A * ptra = dynamic_cast<A*>(©a);
delete ptra;
B b;
A ©b = b.clone();
B * ptrb = dynamic_cast<B*>(©b);
delete ptrb;
return 0;
}
Yes. Unfortunately all that is legal from what I can see. I
have to say though, and excuse the blunt nature of this, I'd
probably fire anyone that wrote anything like this...it's that
horrible.
I sort of agree, taking the code globally. But for reasons more
or less orthogonal to his original question. Something like:
class A
{
public:
virtual ~A() {}
virtual A& clone() const { return *new A ; }
} ;
class B : public A
{
public:
virtual A& clone() const( return *new B ; }
} ;
int
main()
{
A& a = *new A ;
A& copyA = a.clone() ;
delete &a ;
delete ©A ;
A& b = *new B ;
A& copyB = b.clone() ;
delete &b ;
delete ©B ;
return 0 ;
}
might be considered reasonable, IF it conforms to the local
coding conventions. I've never seen a place which used such
conventions, however, and I'd argue against such a convention,
precisely because it is so rare (and thus surprising).
Everywhere I've worked, or heard of, the convention has been to
use pointers for intermediate values whenever the final
operation would require a pointer; i.e. to avoid situations
which require taking the address of a reference.
--
James Kanze