Some time ago to interview, was asked a question, suddenly do not know how to answer, and then check the check, just know how the original is, now summed up.
Copy constructors and assignment operators are used to create replicas of objects. In some cases, a copy constructor is implicitly invoked by the compiler, such as when an object is passed by value.
Advantages:
Copy constructors make it easy to copy objects. The STL container requires all content to be copied and assigned. Copy constructors can be more efficient than copyfrom () solutions because they combine construction and replication.
Disadvantages:
An implicit copy of an object is one of the sources of error and performance problems in C + +. It also reduces the readability of the code and makes it difficult to trace the transfer and change in the object subroutine.
Only a few classes require a copy. The vast majority of classes need neither copy constructors nor assignment operator functions. In most cases, using pointers or references can accomplish the same tasks and have better performance. For example, you can pass arguments to a function by reference or pointer, rather than by value. storing pointers to objects in STL containers, rather than storing copies of objects.
If your class requires a copy, you can provide a method for copying, such as CopyFrom () or clone (), rather than using a copy constructor, because this method cannot be implicitly invoked by the compiler. If the provided replication method is not sufficient, consider providing both the copy constructor and the assignment operator function in specific cases (such as performance reasons, or because your class needs to be stored in the STL container by value).
If your class does not need to copy constructors or assignment operator functions, you must explicitly disable them. To do this, you can add the null declaration of the copy constructor and assignment operator functions in the Private (private) section of the class, but do not provide any corresponding definitions. Therefore, any attempt to use them will result in link errors (links error).
For convenience, you can use the Disallow_copy_and_assign macro:
A macro to disallow the copy constructor and operator= functions
//This should is used in the Private:declaration s for a class
#define DISALLOW_COPY_AND_ASSIGN (TypeName) \
TypeName (const typename&); \
void operator= (const typename&)
Then use this in class Foo:
class Foo {public
:
foo (int f);
~foo ();
Private:
disallow_copy_and_assign (Foo);
That's good.