This code fails at runtime in the copy constructor.
But the compiler (MSVS2008) issues no warnings.
Could you explain (preferably cite the standard) whether this
According to the standard (12.6.1 [class.expl.init] ) self initialization is perfectly legal.
Therefore the following is legal.
A a = a;
You just need to write your copy constructor to deal with it correctly.
A(const A& rv)
{
if(&rv == this) {
p = new int(0);
return;
}
p = new int(*rv.p);
}
Edit: Updated code based on comments.
Interesting reading on self-assignment: http://www.gotw.ca/gotw/011.htm
In particular, note "Postscript #1" in relation to this question and some of the answers given.
A a = a;
definitely should not be written. But a = a
could be written. Your assignment operator must check for &rv == this
and do nothing in case of a self-copy.
Oh, yes, you do need to write an assignment operator for class A.
Your code is not calling the standard constructor but the copy constructor, so you are accessing an uninitialized pointer.