Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Jul 23, 1998

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
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap