Avoiding default copy constructor and assignment operator..
Recently i got an article somewhere on web about forgetting declaring a parameter type as a pointer while making a function call, then the compiler gladly copies the object onto the stack and calls the function. For a class with a lot of member variable storage, this can be costly in execution time and In stack space.
to avoid this...
In C++ to be able to pass a parameter by value the compiler needs what is called a copy constructor. If your application performs some operation that needs a copy constructor, the compiler will write one for you and call it unless you provide your own. You can prevent the compiler from writing the copy constructor by declaring the copy constructor in the private area of your class, and then not provide an implementation. It is private so that no one can call it (except the class itself), and it is not implemented to make sure it uses no space and cannot even be called by the containing class.
The same problem exists for returning an object by value. The compiler will then need a copy constructor and an assignment operator. You can use the same technique above to declare a private undefined assignment operator and prevent the whole problem.
Every time I create a class in C++ I always start with a class that looks like this:
ClassName(); //the default constructor
//Degenerate copy and assignment
ClassName& operator=(const ClassName&)
Following this simple technique prevents the compiler from writing this code for you and prevents calling the code as well.
what i am not able to understand is...
In the case, when we pass the object by value and also in the case when the object is returned by value and using the above trick, how things work then, i mean how complier will treat these objects which are passed or returned by value, will then there be no copies created and pointers will be used by compiler. how the complier react when it cant make its own versions of copy constructor or assignment operator nor it can use any other, as in above piece of code both are in private and UNimplemented...??? :confused:
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL