jeudi 25 janvier 2018

Copy constructor called on *this

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.

  1. 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.

  2. Should I defensively check this==&rhs whenever I define a copy constructor?

I am using gcc version 5.4.0 with -std=c++11.

Aucun commentaire:

Enregistrer un commentaire