A period of time to interview, was asked a question, suddenly do not know how to answer, and then check the check, just know how it is, now summarize it.
The copy constructor and assignment operators are used to create a copy of the object. In some cases, the copy constructor is implicitly called by the compiler, such as when the object is passed by value.
Advantages:
Copy constructors make it easy to copy objects. STL containers require 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 track the delivery and changes in the object subroutine.
Only a few classes need to be copied. Most classes do not need to copy constructors or assign operator functions. In most cases, using pointers or references can accomplish the same task and have better performance. For example, you can pass arguments to a function by reference or by pointer rather than by value. Stores a pointer to an object in an STL container, rather than a copy of the stored object.
If your class needs to be copied, you can provide methods for replication, such as CopyFrom () or clone (), instead of using the copy constructor, because this method cannot be called implicitly by the compiler. If you provide a copy method that is not sufficient, under specific circumstances (for example, for performance reasons, or because your class needs to be stored by value in an STL container), consider providing both a copy constructor and an assignment operator function.
If your class does not need to copy constructors or assignment operator functions, you must explicitly disable them. To do this, you can add a null declaration of the copy constructor and the assignment operator function in the private section of the class, but do not provide any corresponding definitions. Therefore, any attempt to use them will result in link errors.
For convenience, you can use the Disallow_copy_and_assign macro:
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations 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 would be good.
Advantages and disadvantages of C + + copy constructors