Beware of Aliasing

Whenever your class contains pointers, references, or handles, you need to define a copy constructor and assignment operator. Otherwise, the compiler-generated copy constructor and assignment operator will result in aliasing, that is to say, the same resource will be used simultaneously by more than one object and will also be released more than once – with disastrous results:

 class Document {private:	FILE *pdb;public:	Document(FILE *f =NULL) : pdb(f){}  //no user-defined copy constructor or operator=	~Document() {fclose(pdb);}	//...};void assign(Documnet d&){Document temp("letter.doc");d = temp;  //Aliasing; both d and temp now point to the same file}//temp's destructor is now automatically called and closes file letter.doc while d is still using it  void main() {Document doc;assign(doc);//OOPS! doc now uses a file which has just been closed }//OOPS! doc's destructor is now invoked and closes 'letter.doc' once again
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: