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


advertisement
 

Blocking Undesirable Object Copying and Implicit Conversions-3 : Page 3

C++ doesn't offer a direct mechanism for blocking undesirable copying or preventing implicit conversion of arguments. However, with some code tweaks you can work around these problems.


advertisement

Blocking Copying and Assignment
A previous 10-Minute Solutiondemonstrated a technique for blocking object copying—but it has a flaw which calls for revision.

As said earlier, there's no way to instruct the compiler to not declare a copy constructor and an assignment operator implicitly as public members of the class—unless youdeclare them explicitly. If you declare these members explicitly as private members, they will become inaccessible and, hence, unusable:


class Myfile
{
private:
 Myfile(const Myfile&); //block copying
 Myfile& operator=(const Myfile&); //block assignment

public:
 explicit Myfile(const char * name);
 Myfile();
 virtual ~Myfile();
 virtual int open(const char * name);
 virtual int close();
};


Notice how the private copy constructor and assignment operators block copying and assignment:


int main()
{
 Myfile datafile("mydata.txt");//OK
 Myfile file2(datafile);//error, copy ctor inaccessible
 Myfile third;
 third=file2; //error, assignment op inaccessible
}

This technique differs in one crucial aspect from the technique shown in the previous 10-Minute solution. In the code above, the private member functions are only declared; they are not implemented. If you implement the private copy constructor and the assignment operators, any member function of Myfilewill be able to invoke them. Using the new technique, the program will fail to link should a member function invoke the copy constructor or assignment operator.



Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap