class Empty
{
public:
Empty(); //缺省构造函数
Empty(const Empty&); //拷贝构造函数
~Empty(); //析构函数
Empty& operator=(const Empty&); //赋值运算符
Empty* operator&(); //取值运算符
const Empty* operator&() const; // 取值运算符
};
For example, you have the following class:
class StringBad
{
private :
char * str;
int len;
public :
StringBad( const char * s);
StringBad();
~ StringBad();
} ;
The following definitions are defined in the constructor and destructor functions:
StringBad::StringBad( const char * s)
{
len = std::strlen(s);
str = new char [len + 1 ];
}
StringBad::StringBad()
{
len = 4 ;
str = new char [ 4 ];
}
StringBad:: ~ StringBad()
{
delete [] str;
}
So in the program, if you have the following code:
Stringbad Sports ("Spinach Leaves Bow1 for bollars");
Stringbad sailor = sports;
What constructor will be called for the second initialization statement above? Remember that this form of initialization is equivalent to the following statement:
Stringbad sailor = Stringbad (sports);
Because the sports type is Stringbad, the corresponding constructor prototype should be as follows:
Stringbad (const Stringbad &);
When we use an object to initialize another object, the compiler automatically generates the above constructor, called the copy constructor, because it creates a copy of the object.
Now let's see what happens when we call an implicit copy constructor without defining a copy constructor.
As you can see from the code fragment defined by the constructor, a pointer str is initialized with the new operator, and the implicit copy constructor is replicated by value, and for pointer str, the following replication occurs:
Sailor.str = Sports.str;
This copy is not a string, but a pointer to a string! In other words, we'll get two pointers to the same string! The problems that arise from this will be self-evident. When one of the objects calls the destructor, the memory that its STR points to will be freed, and when we call another object, what is the address data that Str points to? It is clear that unpredictable results will occur.