Reputation: 841
I defined a copy constructor for a class A
. Due to an unfortunate macro expansion, I ended up compiling the following:
A a = a;
I (eventually) realized this results in a call to A::A(const A& rhs)
with this==&rhs
.
Why does the compiler allow this? Conceptually I would assume that since a
is declared in this statement, it wouldn't yet be available for use on the RHS.
Should I defensively check this==&rhs
whenever I define a copy constructor?
I am using gcc version 5.4.0 with -std=c++11
.
Upvotes: 0
Views: 32
Reputation: 141598
In a declaration, the identifier being declared is in scope as soon as it appears. There are some valid uses of this, e.g. void *p = &p;
It's normal for the copy-constructor to assume no self-copy, leaving it up to the caller to not make this mistake. Preferably, follow the rule of zero.
It would be better to not write A a = a;
in the first place. To avoid this you could get in the habit of using auto
, e.g.
#define F(x) auto a = A(x)
#define G(x) A a = x
Now if you write G(a);
you silently get the bug, but F(a);
fails to compile.
Upvotes: 1