Beware of Aliasing

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

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist